我對於 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
。有誰能給我解釋下是什麼原因?謝謝!
它在 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();
}