如何为 HTTP Post 添加超时
为什么代码对我不起作用,即使连接已经过时,(服务器很长时间没有响应,代码也没有抛出任何异常!
try{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 3000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpPost post = new HttpPost("url");
post.setParams(httpParameters);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("ab ", cd));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
while ((line = rd.readLine()) != null)
{
}
}
catch(java.net.SocketTimeoutException e4)
{
Toast.makeText(xyz.this, "Your connection is stale", 10000).show();
}
catch (IOException e2)
{
Log.d("G22", "Entered Exception");
}
catch (Exception e2)
{
Toast.makeText(xyz.this, "Your connection is stale..", 10000).show();
e2.printStackTrace();
Log.d("G22", "Entered Exception");
}
Why the code is Not working for me, Even the connection is stale, (there is no response from the server for a long time, the code is not throwing any exception!
try{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 3000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpPost post = new HttpPost("url");
post.setParams(httpParameters);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("ab ", cd));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
while ((line = rd.readLine()) != null)
{
}
}
catch(java.net.SocketTimeoutException e4)
{
Toast.makeText(xyz.this, "Your connection is stale", 10000).show();
}
catch (IOException e2)
{
Log.d("G22", "Entered Exception");
}
catch (Exception e2)
{
Toast.makeText(xyz.this, "Your connection is stale..", 10000).show();
e2.printStackTrace();
Log.d("G22", "Entered Exception");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须使用
HttpClient
和HttpPost
吗?您可以使用HttpURLConnection
,它具有setConnectTimeout(int)
方法:参见我的回答此处查看使用
HttpsURLConnection
进行 POST 操作的示例。Do you have to use
HttpClient
andHttpPost
? You could use anHttpURLConnection
, which has thesetConnectTimeout(int)
method:See my answer here for an example of using
HttpsURLConnection
for a POST operation.你可以使用这个代码
U can Use this code