httpclient本地网不通怎么设置连接超时

2025-03-18 08:35:42
推荐回答(1个)
回答1:

有时使用httpclient的时候,需要等待N长时间,可能此时你决定放弃或者重试。实现上非常简单添加一个参数即可

//这里的超时单位是毫秒。这里的http.socket.timeout相当于SO_TIMEOUT  
httpClient.getParams().setIntParameter("http.socket.timeout",3000);
HttpConnectionManagerParams managerParams   
  = httpClient.getHttpConnectionManager().getParams();  
// 设置连接超时时间(单位毫秒)  
 managerParams.setConnectionTimeout(30000);  
// 设置读数据超时时间(单位毫秒)  
 managerParams.setSoTimeout(120000);

1,设置get方法请求超时为 5 秒

GetMethod getMethod= new  GetMethod(url);     
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,5000 );

2,设置 Http 连接超时为5秒

HttpClient httpClient= new  HttpClient();    
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000 );

设置连接超时和请求超时,这两个超时的意义不同,需要分别设置。