gpt4 book ai didi

java - Android 的 HttpResponse 和超时

转载 作者:行者123 更新时间:2023-12-01 18:58:15 26 4
gpt4 key购买 nike

我希望我的设备在 5 秒后放弃 http 连接。但我的代码不起作用...关闭网络时我从未收到任何超时消息。就像设备仍然尝试连接一样,尽管超时......

有想法吗?我是否试图捕获正确的异常?

谢谢。

        try 
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);

HttpResponse response = httpclient.execute(httppost);

if (response.getStatusLine().getStatusCode() < 400)
{
... //data processing
}
else
{
errorMsgId = R.string.http_site_error;
}
}
catch (ConnectTimeoutException e)
{
Toast.makeText(this, "Network timeout reached!", Toast.LENGTH_SHORT).show();
Log.e("+++++++++++++++++ ","Network timeout reached!");
}

最佳答案

好的,明白了,以防万一这可以帮助其他人:

                    HttpClient httpclient = new DefaultHttpClient();
final HttpParams httpParams = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);

关于java - Android 的 HttpResponse 和超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13253536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com