DefaultHttpClient超时

时间:2013-04-18 16:28:28

标签: java android timeout httpclient

我对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。谁能帮我澄清这个?

2 个答案:

答案 0 :(得分:15)

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

答案 1 :(得分:1)

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

更具体地说,我相信如果在您配置的连接超时内无法建立连接,他们将ConnectTimeoutExceptionsSocketTimeoutExceptions,如果已设置但未收到任何数据为你配置的SO超时。