代码卡在 http execute

Code getting stuck at http execute

我有一个使用 http post 的代码,它工作正常,但有时它会卡在 http.execute 并且在等待响应时没有继续。那么遇到这种情况怎么办呢?

我没有收到任何说无法连接或类似的错误。它只是卡在那里。

这是我的代码

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

那么是否可以在一段时间后使该语句超时,以便代码可以继续?

看看this question。它显示了如何设置超时。

来自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);

还有来自用户 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.