2

I have a code where I am using http post which works fine but sometimes it get stuck at http.execute and did not go ahead as it waits for response. So what can be done in such case?

I am not getting any error that says cannot connect or something like that. It just gets stucked there.

Here is my code

HttpClient client = new DefaultHttpClient();
HandleWebserviceCallPojo pojo = getpojo(sessionId);
String url = "http:x.y.z:8080//"; // my url
logger.info("------------------------------------------------------------");
logger.info("Sending response to client's url..");
logger.info("url-->" + url);

HttpPost post = new HttpPost(url.trim());
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
//the code gets stucked at client.execute and there is no way out after that
logger.info("------------------------------------------------------------");
logger.info("response" + response);

So is it possible to timeout that statement after some time so that code can move ahead?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
kirti
  • 4,499
  • 4
  • 31
  • 60

1 Answers1

1

Take a look at this question. It shows how you can set a timeout.

From Laz:

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
...
// set the connection timeout value to 30 seconds (30000 milliseconds)
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
client = new DefaultHttpClient(httpParams);

There is also a helpful comment from user benvolioT

Apache's HttpClient has two separate timeouts: a timeout for how long to wait to establish a TCP connection, and a separate timeout for how long to wait for a subsequent byte of data. HttpConnectionParams.setConnectionTimeout() is the former, HttpConnectionParams.setSoTimeout() is the latter.

mittmemo
  • 2,062
  • 3
  • 20
  • 27