DefaultHttpClient中的超时时间



我对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)方法,但它只告诉我它抛出了ClientProtocolExceptionIOException。有人能帮我澄清一下吗?

execute()上抛出异常。SocketTimeoutException的父节点是IOException。处理IOException的catch块将能够同时捕获两个。

试着执行这段代码。

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

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

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

相关内容

  • 没有找到相关文章

最新更新