public static void main(String[] args) { HttpClient client = new HttpClient(); HttpMethod method = new GetMethod( "http://test.com"); client.getHttpConnectionManager().getParams() .setConnectionTimeout(3000); client.getHttpConnectionManager().getParams().setSoTimeout(3000); try { int statusCode = client.executeMethod(method); System.out.println(statusCode); byte[] responseBody = null; responseBody = method.getResponseBody(); String result = new String(responseBody); System.out.println(result); } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3:测试的时候,将url改为一个不存在的url:“http://www.111cn.net"
4:超时时间3000ms过后,系统报出异常。
代码如下
复制代码
org.apache.commons.httpclient.ConnectTimeoutException: The host did not accept the connection within timeout of 3000 ms
at org.apache.commons.httpclient.protocol.ReflectionSocketFactory.createSocket(ReflectionSocketFactory.java:155) at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:125) at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
二:读取数据超时:soTimeout
1:指的是连接上一个url,获取response的返回等待时间
2:设置方法
代码如下
复制代码
public class TestHttpClientMain {
public static void main(String[] args) { HttpClient client = new HttpClient(); HttpMethod method = new GetMethod( "http://localhost:8080/firstTest.htm?method=test"); client.getHttpConnectionManager().getParams() .setConnectionTimeout(3000); client.getHttpConnectionManager().getParams().setSoTimeout(2000); try { int statusCode = client.executeMethod(method); System.out.println(statusCode); byte[] responseBody = null; responseBody = method.getResponseBody(); String result = new String(responseBody); System.out.println(result); } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(Unknown Source) at java.io.BufferedInputStream.fill(Unknown Source) at java.io.BufferedInputStream.read(Unknown Source) at org.apache.commons.httpclient.HttpParser.readRawLine(HttpParser.java:78) at org.apache.commons.httpclient.HttpParser.readLine(HttpParser.java:106) at org.apache.commons.httpclient.HttpConnection.readLine(HttpConnection.java:1116) at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1973) at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1735)