Multipart File upload using Apache REST client - java

I was trying to upload files to OneDrive using multipart request. I've tried many ways but none of them worked.
The request is of the form :-
POST /drive/items/{folder-id}/children
Content-Type: multipart/related; boundary="A100x"
--A100x
Content-ID: <metadata>
Content-Type: application/json
{
"name": "newfile.txt",
"file": {},
"#content.sourceUrl": "cid:content",
"#name.conflictBehavior": "rename"
}
--A100x
Content-ID: <content>
Content-Type: text/plain
Contents of the file to be uploaded.
--A100x--
I've tried many ways. The snippet I've done for this added below. Any help would be appreciated.
Snippet :-
HttpClient httpClient = HttpClientBuilder.create().build();
URIBuilder uriBuilder = new URIBuilder(URI);
HttpPost post = new HttpPost(uriBuilder.build());
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
Charset chars = Charset.forName("utf-8");
builder.setCharset(chars);
post.setEntity(builder.build());
builder.addPart("content", new FileBody(new File("/home/myfiles/test"), ContentType.APPLICATION_OCTET_STREAM, "test"));
builder.addPart("metadata", new StringBody(metaJson, ContentType.APPLICATION_JSON));
post.setHeader("Content-Type", "multipart/form-data");
post.addHeader("Authorization", "Bearer " + ACCESS_TOKEN);
try {
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
responseBuilder = new StringBuilder();
while ((output = br.readLine()) != null) {
responseBuilder.append(output);
}
} else {
System.out.println("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
URI :
https://api.onedrive.com/v1.0/drive/root:/myfiles/children

Later on I realized that I can use simple file upload provided my files are simple doc files. And achieved solution using Apache REST client.
Code snippet :-
BufferedReader br = null;
String output;
StringBuilder responseBuilder = null;
HttpClient httpClient = HttpClientBuilder.create().build();
URIBuilder uriBuilder = new URIBuilder(<UPLOAD_URL>);
HttpPut request = new HttpPut(uriBuilder.build());
request.addHeader("Authorization", "Bearer " + oneDriveConnection.getAccessToken());
request.addHeader("Content-Type", mimeType);
HttpEntity entity = new ByteArrayEntity(bytes);
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == 201 || responseCode == 200) {
br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
responseBuilder = new StringBuilder();
while ((output = br.readLine()) != null) {
responseBuilder.append(output);
}
} else {
logger.error("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
throw new UploadException("Upload failure, Status code : " + response.getStatusLine().getStatusCode());
}

Related

How to get response from HttpPost

I want to get response from the httppost request. I get the network response like 200,405,404 but i don't get the value which is coming from server. I am trying a lot but i don't get response. Please help...
My code is below-
private void UploadPost() {
SharedPreferences sharedPreferences1 = getSharedPreferences("DATA", Context.MODE_PRIVATE);
String ID = sharedPreferences1.getString("id", "");
#SuppressWarnings("deprecation")
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Url.addOffer_url);
Log.e("uploadFile", "Source File Path " + picturePath);
File sourceFile1 = new File(picturePath);
if (!sourceFile1.isFile()) {
Log.e("uploadFile", "Source File Does not exist");
imgUploadStatus = "Source File Does not exist";
}
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity();
File sourceFile = new File(picturePath);
MultipartEntity entity1 = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// Adding file data to http body
entity.addPart("retailer_id", new StringBody(ID));
entity.addPart("title", new StringBody(addoffertitle));
entity.addPart("description", new StringBody(addofferdesc));
entity.addPart("keyword", new StringBody(addofferkeyword));
entity.addPart("offer_id", new StringBody(OfferListing_Id));
// entity.addPart("payment_status",new StringBody(paymentStatus));
// if(!picturePath.equals(""))
entity.addPart("offer_image", new FileBody(sourceFile));
/* else
entity.addPart("old_pic",new StringBody(Image_Path));*/
httppost.setEntity(entity);
Log.d("httppost success", "httppost");
//Run a api for net conn check
try {
String responseString= new String();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity8 = response.getEntity();
if(entity8 !=null){
responseString = EntityUtils.toString(entity8, "UTF-8");
System.out.println("Response body: " + responseString);
}
statusCode = 200;
} catch (FileNotFoundException e) {
Log.e("log_tag1", "Error FileNotFoundException new service" + e.toString());
result = "FileNotFoundException";
} catch (SocketTimeoutException e) {
Log.e("log_tag2", "SocketTimeoutException new service " + e.toString());
result = "SocketTimeoutException";
} catch (Exception e) {
Log.e("log_tag3", "Error converting OtherException new service " + e.toString());
result = "OtherException";
}
if (statusCode == 200) {
// Server response
responseString = "success";
Log.e("complete success", "Response from server: " + responseString);
} else if (statusCode == 404) {
responseString = "page not found";
Log.e("complete page not found", "Response from server: " + responseString);
} else if (statusCode == 405) {
responseString = "no net";
Log.e("complete no net", "Response from server: " + responseString);
} else {
responseString = "other";
Log.e("complete other", "Response from server: " + responseString);
}
} catch (Exception e) {
responseString = e.toString();
responseString = "other";
Log.e("complete", "Response from server: " + responseString);
}
}
I want to response from the httppost.i get the network response but i don't get the value which is coming from server.I am trying a lot but i don't get response.Please help...
Try using EntityUtils instead of the BufferedReader. For instance, something like:
String responseString= new String();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if(entity !=null){
responseString = EntityUtils.toString(entity, "UTF-8");
}
Look at the selected answer here - it shows how to get response body for a 400-HTTP response. You can also look at this example. If you are working with JSON payload, perhaps you might want to consider using Volley - here are some examples for PUT, POST, and GET requests using Volley
You can try this
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
Instead of
HttpEntity entity8 = response.getEntity();
if(entity8 !=null){
responseString = EntityUtils.toString(entity8, "UTF-8");
System.out.println("Response body: " + responseString);
}

HTTPClient "main" java.lang.NoSuchFieldError: INSTANCE at org.apache.http.conn.ssl.SSLConnectionSocketFactory.<clinit>

I'm using Httpclient-4.5.2.jar and httpcore-4.4.4.jar HttpClient components and I'm getting below error.
Exception in thread "main" java.lang.NoSuchFieldError: INSTANCE
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.<clinit>(SSLConnectionSocketFactory.java:144)
at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:966)
My source code as follows.
try {
System.out.println("came to try catch");
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("https://bizz.mobilezz.lk/apicall/loanprepaidapi/v1");
StringEntity params =new StringEntity("{\"mobile\":\"776037285\",\"path\":\"IVV\",\"loanAmount\":\"200000\"}");
request.addHeader("content-type", "application/json");
request.addHeader("Authorization", "Bearer casmk34233mlacscmaacsac");
request.addHeader("Accept", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
System.out.println("response is :"+response.getStatusLine());
} catch (Exception e) {
e.printStackTrace();
Please assist me to get rid of this error. I'm trying to send request in post method and get json response.
I found an answer to my question and posting for your reference.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"https://bizz.mobilezz.lk/apicall/loanprepaidapi/v1");
JSONObject json = new JSONObject();
StringEntity params = new StringEntity("{\"msisdn\":\"" + mobile
+ "\",\"channel\":\"SDD\"}");
new StringEntity(json.toString());
post.addHeader("Host", "mife.dialog.lk");
post.addHeader("content-type", "application/json");
post.addHeader("Authorization", "Bearer " + access_token);
post.addHeader("Accept", "application/json");
// System.out.println("status code is:" + status);
post.setEntity(params);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
System.out.println("status code is :" + status);
resCode = Integer.toString(status);
if (status != 401) {
if (status != 409) {
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity()
.getContent()));
String response1 = readAll(rd);
System.out.println(response1);
JSONObject obj = new JSONObject(response1);
resCode = obj.getString("resCode");
resDesc = obj.getString("resDesc");
System.out.println(resCode);
System.out.println(resDesc);
}
}
System.out.println("reason code is :" + resCode);

POST request to REST API with JSON object as payload

I am trying to get the JSON response from the REST API using the POST request that has JSON payload (should be converted to URL encoded text before sending). I have followed some tutorials to implement the process but I get error with status code 400. I may not be encoding the given JSON string or missing something. Please help me solve this problem. Thanks.
Here is my code
try {
URL url = new URL("https://appem.totango.com/api/v1/search/accounts/health_dist");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("app-token", "1a1c626e8cdca0a80ae61b73ee0a1909941ab3d7mobile+testme#totango.com");
conn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
conn.setRequestProperty("X-Requested-With","XMLHttpRequest");
String payload = "{\"terms\":[{\"type\":\"totango_user_scope\",\"is_one_of\":[\"mobile+testme#totango.com\"]}],\"group_fields\":[{\"type\":\"health\"}]}";
OutputStream os = conn.getOutputStream();
os.write(payload.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
After following many posts and tutorials for more than 24 hours I got to know that I am not sending my URL parameters correctly. And also I learned that REST API call using ApacheHttpClient is comparatively easier. I resolved my HTTP error code 400 and got the response back from the server. Here is the working code for my issue.
try {
httpClient = HttpClients.createDefault();
httpPost = new HttpPost("https://appem.totango.com/api/v1/search/accounts/health_dist");
List<NameValuePair> headers = new ArrayList<NameValuePair>(); //ArrayList to store header parameters
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); //ArrayList to store URL parameters
urlParameters.add(new BasicNameValuePair("query","{\"terms\":[{\"type\":\"totango_user_scope\",\"is_one_of\":[\"mobile+testme#totango.com\"]}],\"group_fields\":[{\"type\":\"health\"}]}"));
headers.add(new BasicNameValuePair("app-token", "1a1c626e8cdca0a80ae61b73ee0a1909941ab3d7mobile+testme#totango.com"));
headers.add(new BasicNameValuePair("Accept", "application/json, text/javascript, */*; q=0.01"));
headers.add(new BasicNameValuePair("X-Requested-With", "XMLHttpRequest"));
httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
for (NameValuePair h : headers)
{
httpPost.addHeader(h.getName(), h.getValue());
}
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
response.close();
httpClient.close();
}catch(Exception ex) {
ex.printStackTrace();
}
}
The API you are invoking needs a query parameter called "query=true|false".
URL url = new URL("https://appem.totango.com/api/v1/search/accounts/health_dist?query=true");
After adding this param, the HTTP request itself succeeds with status code 200, but the REST call fails with some server side error. Maybe you need a different payload.
I suggest if you are new to REST, try a REST client like POSTMan

HTTP/1.1 400 Bad Request Apache

I'm attempting to login to twitter using the following code I've written. The issue is on each execution i receive a 400 Bad Request back as the response. I have tried numerous attempts to get this to work to no avail.
public void login(String url) throws ClientProtocolException, IOException{
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
// set cookies
setCookies(response.getFirstHeader("Set-Cookie") == null ? "" : response.getFirstHeader("Set-Cookie").toString());
Document doc = Jsoup.parse(result.toString());
System.out.println(doc);
// Get input elements
Elements loginform = doc.select("div.clearfix input[type=hidden][name=authenticity_token]");
String auth_token = loginform.attr("value");
System.out.println("Login: "+auth_token);
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add(new BasicNameValuePair("authenticity_token", auth_token));
paramList.add(new BasicNameValuePair("session[username_or_email]", "twitter_username"));
paramList.add(new BasicNameValuePair("session[password]", "twitter_password"));
System.out.println(paramList);
HttpPost post = new HttpPost(url);
// add header
post.setHeader("Host", "twitter.com");
post.setHeader("User-Agent", USER_AGENT);
post.setHeader("Accept", "text/html,application/xhtml;q=0.9,*/*;q=0.8");
post.setHeader("Accept-Language", "en-US,en;q=0.5");
post.setHeader("Keep-Alive", "115");
post.setHeader("Cookie", getCookies());
post.setHeader("Connection", "keep-alive");
post.setHeader("Referer", "https://twitter.com/");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(paramList));
// Execute POST data
HttpResponse res = client.execute(post);
int responseCode = res.getStatusLine().getStatusCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + paramList);
System.out.println("Response Code : " + responseCode);
System.out.println("Headers: "+res.getAllHeaders().toString());
System.out.println("Response: "+res.getStatusLine());
BufferedReader rd1 = new BufferedReader(
new InputStreamReader(res.getEntity().getContent()));
StringBuffer resul = new StringBuffer();
String line1 = "";
while ((line1 = rd1.readLine()) != null) {
resul.append(line1);
}
Document doc2 = Jsoup.parse(res.toString());
System.out.println(doc2);
}
public static void main(String[] args) throws ClientProtocolException, IOException{
Browser b = new Browser();
b.login("https://twitter.com/login");
}
I believe that everything that needs to be POST'd is being, such as the username, password, as well as the authenticity token.
Turns out i was sending the wrong session information in my POST request! If anyone else has a similar issue i recommend using Chrome Developer tools to inspect the headers being sent/received.

Problems connecting with a PHP: withg java.lang.Exception: HTTP error: 401

I have this code, who should connect to a php remote file and should get a String representing a XML file. But something is wrong, it is giving me error 401.
The variable url is the direction of the php:
String response=getXML("http://ficticiousweb.com/scripts/getMagazinesList.php");
If i paste the real direction (that is a ficticious direction) on the webbrowser, it works and gives me the XML.
This is my code:
public String getXML(String url){
try{
StringBuilder builder = new StringBuilder();
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
int statuscode = response.getStatusLine().getStatusCode();
if(statuscode == 200)
{
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) builder.append(line);
}
else throw new Exception("HTTP error: " + String.valueOf(statuscode));
return builder.toString();
}catch(Exception e){e.printStackTrace();}
return null;
}
What is wrong with the code?
thanks
You need to login to the requested site in order to download or access the xml. This can be done by authenticated schema based upon what is supported. Normally, there are 2 types of schemas where used. Basic and Digest. Below code will help you for BASIC AUTH.
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String _username = "username";
String _password = "password";
try {
((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(
new org.apache.http.auth.AuthScope(webhostname, webport)),
new org.apache.http.auth.UsernamePasswordCredentials(_username, _password));
response = httpclient.execute(new HttpGet(completeurlhere));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK) {
try {
InputStream is = response.getEntity().getContent();
this._data = is;
} catch(Exception ex) {
Log.e("DBF Error",ex.toString());
}
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch(ClientProtocolException cpe) {
Log.e("ClientProtocolException # at FPT",cpe.toString());
} catch(Exception ex) {
Log.e("Exception at FETCHPROJECTASK",ex.toString());
}
Well a 401 means you aren't Authorized to do the GET request. You should ask the website how to Authenticate the request...
Authorization happens through the Authorization Header in the HTTP request. You should look into that and probably fill that header yourself with your credentials... (if the server accepts that)

Categories

Resources