Blank Response when doing JSON POST from Android - android

I am trying to post two json encoded values to my webservice using the below code. but i am not getting any response (Just Blank Output and No errors on LogCat). However, I have tried posting the same parameters from PHP to my webservice using cURL which works great.
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
try {
json.put("name","email");
json.put("email", "email");
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept-Encoding", "application/json");
post.setHeader("Accept-Language", "en-US");
List<NameValuePair> ad = new ArrayList<NameValuePair>(2);
ad.add(new BasicNameValuePair("json", json.toString()));
post.setEntity(new UrlEncodedFormEntity(ad));
Log.i("main", "TestPOST - nVP = "+ad.toString());
response = client.execute(post);
if(response!=null) {
HttpEntity entity = response.getEntity();
output = EntityUtils.toString(entity,HTTP.UTF_8); //Get the data in the entity
}
} catch(Exception e) {
}

Try Getting your response by this
if (response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
json = EntityUtils.toString(entity);
}

You're catching Exception (the super class) without logging. If an exception of any kind occurs in your try block the code will jump to the catch without any log.
Change this:
catch(Exception e){
}
with
catch (Exception e)
Log.e("myappname", "exception", e);
}

If there is no response, you should definitely check your catch exception e, since you didn't write anything in the clause, there might be something happening but you didn't notice.

Related

POST request always return html instead of JSON in android

I am building a simple android application where I am making a Login Page and implementing a simple POST web API. Previously it was working fine but suddenly it stops working and now it is always returning me HTML code. Below is my code,
try {
List<NameValuePair> li = new ArrayList<NameValuePair>();
li.add(new BasicNameValuePair("username", "ma#dhdh.com"));
li.add(new BasicNameValuePair("password", "123456dndjsj789"));
li.add(new BasicNameValuePair("key", "ZATXMhjHartjDTrH"));
HttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
HttpPost httppost = new HttpPost("http://www.deal.com.lb/merchant_ws/login_ws.php");
httppost.setHeader("Content-Type", "text/html");
httppost.setHeader("Accept","application/json");
httppost.setEntity(new UrlEncodedFormEntity(li));
httpResponse = httpClient.execute(httppost);
httpEntity = httpResponse.getEntity();
String response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please tell me which code I had wrote wrong. Also this service is also working as GET request. You can try it in browser. In browser it is working properly but in Android code it is not.
Have you set header('Content-Type: application/json');
in your PHP? And have you a trace, log of Java-Code?

I have got Socket Timeout Exception but My data submitted on server too

I have got an prob with http post request i have set time out and on socket time out exception my data submitted on server successfully how i can restrict data to submitted on server my code is following
try{HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
AppSettings.SERVICE_URL.POST_NEW_REGISTRATION);
HttpConnectionParams.setConnectionTimeout(
httpClient.getParams(), 5000);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), 5000);
JSONObject jsonObject = new JSONObject();
jsonObject.put("agent_id", SharedPrefrence.getUserID());
httpPost.setEntity(new StringEntity(jsonObject.toString(),
"UTF-8"));
// Set up the header types needed to properly transfer JSON
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
// Execute POST
//int getConnectionTimeout (HttpParams params);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
if (responseEntity != null) {
response = EntityUtils.toString(responseEntity);
} else {
response = "{'success':'FALSE'}";
}
} catch (ClientProtocolException e) {
response = "{'success':'FALSE'}";
progressDialog.cancel();
} catch (IOException e) {
response = "{'success':'FALSE','message':'Connection Time Out'}";
Log.d("Ex", e.toString());
Log.e("Ex", e.toString());
progressDialog.cancel();
} catch (JSONException e) {
response = "{'success':'FALSE','message':'JSON Parse Error'}";
progressDialog.cancel();
e.printStackTrace();
} catch (Exception e) {
response = "{'success':'FALSE'}";
progressDialog.cancel();
e.printStackTrace();
}
I think you are saying that you are getting a socket timeout exception even though the data is successfully received by the server?
If so, I think you may want to look at the value you are setting for the socket timeout - this appears to be 500ms in your code, which is quite short. It is quite possible that everything on the server side is working fine, but that the response is simply not getting to the client within 500ms.
A typical default is in the 6-10 seconds range, but it is really solution dependent so you may want to experiment. This blog post suggests some defaults for different scenarios and may be a useful reference:
http://dev.bizo.com/2013/04/sensible-defaults-for-apache-httpclient.html
probably your API call takes more than 500 ms, increase it and try again.

Posting a JSONArray to WCF Service from android

I am having trouble posting a JSONArray of values to my WCF Service. When I post the data from Fiddler or .Net Test Client it works fine. Every time I try to post from my android application I get Request Error
This is the JSON data that I send to my WCF Service from the android application. I've tried this exact data from Fiddler and it works
[{"date":"2013-02-22 15:30:374:021","id":"1","description":"test","name":"test"},
"date":"2013-02-25 11:56:926:020","id":"2","description":"ghy","name":"fhh"},
"date":"2013-02-25 11:56:248:026","id":"3","description":"ghfm","name":"run"}]
My android code
public JSONObject makeHttpPost(String url, String method, JSONArray params) {
try {
if (method == "POST") {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type",
"application/json; charset=utf-8");
StringEntity se = new StringEntity(params.toString(),"UTF-8");
se.setContentType("application/json;charset=UTF-8");
httpPost.setEntity(se);
Log.e("Gerhard", params.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
My WCF Service
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "updateOrderAddress")]
String UpdateOrderAddress(Stream JSONdataStream);
public String UpdateOrderAddress(Stream JSONdataStream)
{
try
{
// Read in our Stream into a string...
StreamReader reader = new StreamReader(JSONdataStream);
string JSONdata = reader.ReadToEnd();
// ..then convert the string into a single "wsOrder" record.
if (JSONdata == null)
{
// Error: Couldn't deserialize our JSON string into a "wsOrder" object.
return "null";
}
return JSONdata; // Success !
}
catch (Exception e)
{
return e.ToString();
}
}
The error I'm getting
02-26 14:00:56.185: E/Gerhard(31064): <p>The server encountered an error processing the request. The exception message is 'Incoming message for operation 'UpdateOrderAddress' (contract 'IService1' with namespace 'http://tempuri.org/') contains an unrecognized http body format value 'Json'. The expected body format value is 'Raw'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.'. See server logs for more details. The exception stack trace is: </p>
I have called multiple GET requests from android application to same WCF Service and it works great, but now I need to send an array of data to the wcf service. Please please help me.Thanks in advance
remove
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
from ur code

How to handle the situation when server is down on my android side

Here is my doInBackground() method in which I call my makeHttpRequest() method which is in other class.
protected String doInBackground(Integer... args) {
// Building Parameters
String parameter1 = "tenant";
String parameter2 = "price";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("person",parameter1));
params.add(new BasicNameValuePair("price",parameter2));
JSONObject json = jParser.makeHttpRequest(requiredurl, "POST", params);
Log.d("Details", json.toString());
int success = json.getInt("connected");
if (success == 1) {
//blah blah
}
}
makeHttpRequest() method:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
................
....................... // Here the result is extracted and made it to json object
.............................
// return JSON
return jObj; // returning the json object to the method that calls.
}
So, by the above code, the actual call to the server is made by this line -> HttpResponse httpResponse = httpClient.execute(httpPost);
When my server is up everything works fine, but when it is down the progress bar continuously loads. I want to handle this situation. Have done lot of search, but could find only this post. This looks good for my situation because even my thought is to wait for the 10 seconds to get the response and if it exceeds that time out, I need to handle it to show the message in the catch block. But I am unable to implement it according to my code. Can some one please help me on this? I would be very thankful.
Your exceptions are not getting hit because the HttpClient is not throwing an exception. Perhaps you are getting an error in your HttpResponse code, such as a 500. In your try block, add this line:
response.getStatusLine().getStatusCode()
Then read the status code. If your web server is up you should get a 200 OK, but if it's down, you'll probably get a 500 or something else. You can then handle the code here where your spinning progress bar needs to be hidden, and an error message can be displayed.
Add Following Code before executing the url.
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
HttpConnectionParams.setSoTimeout(httpParameters, 30000);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
write the above code in try block and Catch ConnectTimeOutException and SocketConnectionTimeOutException. Where you can show some custom dialog.
You can also judge it by checking the status line of HttpClient Response.

Status code of HTTP response of server in Android phone is printed in the body of response

I am using http://hc.apache.org/httpcomponents-core-ga/httpcore/examples/org/apache/http/examples/ElementalHttpServer.java for Android.
I set the response using the following code:
HttpResponse getResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, 404, "Not Found");
getResponse.setEntity(new StringEntity(new String("The requested resource " + target + " could not be found due to mismatch!!")));
conn.sendResponseHeader(getResponse);
conn.sendResponseEntity(getResponse);
My response in Mozilla Poster or browser has the header 404 and the response body as:
The requested resource could not be found due to mismatch!!HTTP/1.1 200 OK
How can I get only the HTTP body String? Why am I getting HTTP/1.1 200 OK in response. I dont set this in my code. Any help is appreciated.
this might help you...
i think response is what you need
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
there was a problem in my defined handle() method. I was creating a new HttpResponse for each request instead of using the response passed in the
public void handle(HttpRequest request, HttpResponse response, HttpContext context)

Categories

Resources