8

我对 DefaultHttpClient 中的超时如何工作感到有些困惑。

我正在使用这段代码:

private DefaultHttpClient createHttpClient() {
        HttpParams my_httpParams = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(my_httpParams, 3000);
        HttpConnectionParams.setSoTimeout(my_httpParams, 15000);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        ThreadSafeClientConnManager multiThreadedConnectionManager = new ThreadSafeClientConnManager(my_httpParams, registry);

        DefaultHttpClient httpclient = new DefaultHttpClient(multiThreadedConnectionManager, my_httpParams);

        return httpclient;
}

.

String url = "http://www.example.com";

DefaultHttpClient httpclient = createHttpClient();
HttpGet httpget = new HttpGet(url);

try {
    HttpResponse response = httpclient.execute(httpget);
    StatusLine statusLine = response.getStatusLine();
    mStatusCode = statusLine.getStatusCode();

    if (mStatusCode == 200){
        content = EntityUtils.toString(response.getEntity());
    }

} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (IllegalStateException e){
    e.printStackTrace();
}

当 15 秒过去了,还没有收到所有数据,就会抛出异常,对吧?但在哪种方法上?我认为这是.execute(httpget)一种方法,但那个方法只告诉我它会抛出ClientProtocolExceptionand IOException。谁能帮我澄清一下?

4

2 回答 2

16

它确实在execute(). 的父级SocketTimeoutException是一个IOException. catch 块处理IOException将能够同时捕获两者。

尝试执行此代码。

HttpParams my_httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(my_httpParams, 3000);
HttpConnectionParams.setSoTimeout(my_httpParams, 1);
DefaultHttpClient defaultHttpClient = new DefaultHttpClient(my_httpParams);
HttpGet httpGet = new HttpGet("http://google.com");
defaultHttpClient.execute(httpGet);

它导致此异常。

java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(Unknown Source)
    ...
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)

您始终可以选择通过捕获并IOException稍后处理来选择性地处理异常。

try
{
    // Your code
}
catch (SocketTimeoutException e)
{
    // handle timeouts
    e.printStackTrace();
}
catch (IOException e)
{
    // handle other IO exceptions
    e.printStackTrace();
}
于 2013-04-18T16:40:48.517 回答
1

如果您查看http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e249上的 Apache 文档,它会注意到连接超时异常是 IOException 子类。

更具体地说,我相信如果无法在您配置的连接超时内建立连接,他们将要么是ConnectTimeoutExceptions ,要么是SocketTimeoutExceptions,如果它已设置但没有收到您配置的 SO 超时的数据。

于 2013-04-18T16:43:25.937 回答