How to get response from HttpPost - java

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);
}

Related

Call RestFull Web Service inside Servlet

i have a standard HttpServlet in my java web project. I use Netbeans. I want to call a Restfull Web service inside servlet and after i will catch the response like a JSON and populate a JSP.
I tried to find on the net but i didn't find anything.
Thank you
Here's an example of HttpPost:
try {
HttpPost httpPost = new HttpPost("https://exampleurl/providerexample/api/v1/loansforexample"
);
StringEntity params;
params = new StringEntity("{"
+ "\"clientId\": \"" + "2" + "\","
+ "\"productId\": \"" + "1" + "\","
+ "\"locale\": \"" + "en" + "\"}");
httpPost.addHeader("Content-Type", "text/html"); //or text/plain
httpPost.addHeader("Accept-Encoding", "gzip, deflate, sdch");
httpPost.setEntity(params);
HttpResponse response = client.execute(httpPost);
int statuscode = response.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(response.getEntity());
if (statuscode == 200) {
System.out.println(responseBody);
}
if (statuscode != 200) {
System.out.println(responseBody);
// JSONObject obj = new JSONObject(responseBody);
// JSONArray errors = obj.getJSONArray("errors");
// String errorMessage = "";
// if (errors.length() > 0) {
// errorMessage = errors.getJSONObject(0).getString("developerMessage");
}
}
catch (Exception ex) {
ex.printStackTrace();
ex.getMessage();
}
HttpGet is pretty much the same.

Java (Android) HTTP Post to PHP Page

This is for an Android application ,where my mobile developer is trying to post json data to my PHP page .
Below is the function that is being used :
public static String postData(String url, String postData) {
// Create a new HttpClient and Post Header
InputStream is = null;
StringBuilder sb = null;
String result = "";
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new StringEntity(postData));
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
//throw new CustomException("Could not establish network connection");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
//throw new CustomException("Error parsing the response");
}
return result;
}
Where url is the link to my php webpage . On my php page , i am just trying to print out the posted data by doing :
print_r($_POST);
But it shows an empty array . I even tried using the REST addon for firefox and doing the same but it simply shows a blank array .
Would be great if someone could point out if i am missing anything .
Thanks.
you need to get the json content like below :
if(isset($_POST))
{
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);
echo $jsonObj;
}

Retrieve get response with Android

I have an app android that in an AsyncTask make 2 get request to a servlet.
I want to retrieve a String that contains a simple response.
This is my AsyncTask:
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
String responseStr = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
try {
HttpClient client = new DefaultHttpClient();
URI getURL = new URI("http://192.168.1.101:8080/MusaServlet?collection="+collection+"&name="+filename);
Log.i("QUERY",getURL.getQuery());
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
responseStr = EntityUtils.toString(responseGet.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseStr;
}
Instead the servlet code is:
PrintWriter out = response.getWriter();
out.println("HELLO STUPID APP!");
However the dialog showed by app is empty! No words!
What's the problem guys?
Thank's
At first check your GET request status code as
responseGet.getStatusLine().getStatusCode();
If is giving number 200 then GET is successfull.
Now if is 200 then you will get the response what you have sent by following code
HttpEntity resEntityGet = responseGet.getEntity();
and then
String result;
if(resEntityGet !=null ){
result= EntityUtils.toString(resEntityGet);
}
Now the most important thing is once you perform responseGet.getEntity() the data of GET response will be passed to the variable.. you assign.. and later on calling responseGet.getEntity() will always return empty...
That may be the reason you are getting empty response in your dialog
EDIT:
Ok I have modified my code and playing with logcat I'm sure that the responseCode is not 200.
What is the problem now? -.-"

How can i multiple picture send with android

hello i need when i click to button "send" i send all selected picture ( i have all this picture in table picture[]
in PHP i do this
<input id="uploadImageAct" type="file" name="uploadImageAct[]" data-max-size="2048" accept="image/x-png, image/gif, image/jpeg" style="visibility: hidden" multiple="multiple">
and in android for just one picture i do this but i don't know how i do for multi picture (I put all my picture in table picture[] )
this solution is for one image for FileBody and me i need multi image in one FileBody
public JSONObject post(String url, ArrayList<NameValuePair> nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("uploadFile")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
} else {
// Normal string data
Charset chars = Charset.forName("UTF-8");
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue(),chars));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
How can I change this function so that I can do this
thanks :)
You can upload multiple files in one request along with other string parameters in Android.
For that, you have to include 2 libraries into your project build path, apache-mime4j-0.6.jar and httpmime-4.0.1.jar.
private void doFileUpload(){
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
String urlString = "Your server location";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
FileBody bin2 = new FileBody(file2);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("uploadedfile2", bin2);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Or simply visit CoderzHeaven, it may help you.

How can I check if InputStream is sending data or not? (working with GSON)

I didn't find this question on StackOverflow or maybe I searched with loose keywords.
I use to get an InputSteam normally for JSON files on Internet, this is my main function:
static HttpGet getRequest;
static HttpResponse getResponse;
public static InputStream retrieveStream(String url, int timeout) {
getRequest = null;
getResponse = null;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
HttpConnectionParams.setSoTimeout(httpParameters, timeout);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
getRequest = new HttpGet(url);
try {
getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ERROR", "Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
} catch (IOException e) {
getRequest.abort();
Log.w("ERROR", "Error for URL " + url, e);
} catch (Exception e) {
getRequest.abort();
Log.w("ERROR", "Error for URL " + url, e);
}
return null;
}
for the scope of avoiding errors or giving the possibility to the user to cancel the request because Internet is ON but isn't working fine, I would like to make a counter when my app is not receiving data and it's not completed. I know how to do the counter, but, how could I make that type of 'listener'?
I use to continue with this (always Asynchronously):
InputStream source = f.retrieveStream(params[0]);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
response = gson.fromJson(reader, Usuario.class);
thanks in advance.

Categories

Resources