2 znl 12 znl_12 于 2013.05.16 15:18 提问

DefaultHttpClient 中的 Timeout事件

我对于 timeouts 在 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)方法的问题。但是抛出的异常是 ClientProtocolException and IOException。有谁能给我解释下是什么原因?谢谢!

2个回答

CSDN_Ask
CSDN_Ask   2013.05.17 10:23
已采纳

它在 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();
}
yjsxxgm
yjsxxgm   2013.07.09 16:04

报错应该是在这句:HttpResponse response = httpclient.execute(httpget);
我本地测试异常如下:
org.apache.http.conn.ConnectTimeoutException: Connect to www.example.com:80 timed out
我用的是httpclient4.2

Csdn user default icon
上传中...
上传图片
插入图片