I have a method to connect to send post data to a webservice and get the response back as follow:
public HttpResponse sendXMLToURL(String url, String xml, String httpClientInstanceName) throws IOException {
HttpResponse response = null;
AndroidHttpClient httpClient = AndroidHttpClient.newInstance(httpClientInstanceName);
HttpPost post = new HttpPost(url);
StringEntity str = new StringEntity(xml);
str.setContentType("text/xml");
post.setEntity(str);
response = httpClient.execute(post);
if (post != null){
post.abort();
}
if (httpClient !=null){
httpClient.close();
}
return response;
}
Then, in my AsyncTask of my fragment, I try to read the response using getEntity():
HttpResponse response = xmlUtil.sendXMLToURL("url", dataXML, "getList");
//Check if the request was sent successfully
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// Parse result to check success
responseText = EntityUtils.toString(response.getEntity());
if (!xmlParser.checkForSuccess(responseText, getActivity())){
//If webservice response is error
///TODO: Error management
return false;
}
}
And when I reach that line:
responseText = EntityUtils.toString(response.getEntity());
I get an exception: java.net.SocketException: Socket closed.
This behavior doesn't happen all the time, maybe every other time.
Just write
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(your url);
HttpResponse response = client.execute(post);
it should work.No need to write codes which makes confusion.
I also experienced the 'socket closed' exception when using a client instance built using HttpClientBuilder. In my case, I was calling HttpRequestBase.releaseConnection() on my request object within a finally block before processing the response object (in a parent method). Flipping things around solved the issue... (working code below)
try {
HttpResponse response = httpClient.execute(request);
String responseBody = EntityUtils.toString(response.getEntity());
// Do something interesting with responseBody
} catch (IOException e) {
// Ah nuts...
} finally {
// release any connection resources used by the method
request.releaseConnection();
}
Related
I want to fire a blocking call to my php file which queries my db. I want it to be blocking and not async as i don't want the user shown anything until this call is successful or not.
I run the below code, it stops at response = httpclient.execute(httpget); for a minute or two before going into catch for error. I cant see an error in the e item.
Anybody know whats going on here - my php file works with async task.
public static String blockingHttpCallToUrl(String url)
{
String result="nothingReturned";
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda", response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
} catch (Exception e) {}
return result;
}
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.
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.
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)
Anyone ever called the setlist.fm API from Android? I'm trying to execute the following code:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest;
try
{
getRequest = new HttpGet(url);
HttpResponse getResponse = client.execute(getRequest);
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (Exception e)
{
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
return null;
}
But I run into 2 issues it seems. The execute always seems to return correctly with a statusline of 200, but when I try to get the entity the length is -1 even though the response object shows a basichttpentity object was returned. Also, when I try to call getContent it blows up for some reason with a generic exception. A sample API call that I'm trying to use is http://api.setlist.fm/rest/0.1/search/setlists.json?artistName=Prince.
Any suggestions would be gladly welcomed.
Thanks!
I figured out the issue. It seems that the response coming back from the API is streamed and comes in chunks and I was attempting to grab the entity before it was finished. I removed this code:
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
And replaced it with:
return EntityUtils.toString(getResponse.getEntity());