gpt4 book ai didi

java - DefaultHttpClient 超时

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:14:52 26 4
gpt4 key购买 nike

我对 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 block 将能够捕获两者。

尝试执行这段代码。

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

关于java - DefaultHttpClient 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16088378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com