0

我希望我的设备在 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!"); 
        }
4

3 回答 3

3

好的,明白了,所以如果这可以帮助别人:

                    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);
于 2012-11-07T14:16:27.800 回答
1

你可以使用这样的东西:

/**
 * Check availability of web service
 * 
 * @param host Address of host
 * @param seconds Timeout in seconds
 * @return Availability of host
 */
public static boolean checkIfURLExists(String host, int seconds)
{
    HttpURLConnection httpUrlConn;
    try
    {
        httpUrlConn = (HttpURLConnection) new URL(host).openConnection();

        // Set timeouts in milliseconds
        httpUrlConn.setConnectTimeout(seconds * 1000);
        httpUrlConn.setReadTimeout(seconds * 1000);

        // Print HTTP status code/message for your information.
        System.out.println("Response Code: " + httpUrlConn.getResponseCode());
        System.out.println("Response Message: "
                + httpUrlConn.getResponseMessage());

        return (httpUrlConn.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e)
    {
        System.out.println("Error: " + e.getMessage());
        return false;
    }
}
于 2012-11-06T19:01:56.753 回答
0

也许我遗漏了一些东西,但是您在哪里将设置超时的参数与您HttpClient创建的参数相关联?你不应该做这样的事情:

HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
...
HttpClient httpclient = new DefaultHttpClient(httpParameters);
于 2012-11-06T15:29:24.707 回答