天天看点

3.2.6 HttpClient超时设置

//程序3-18
public class HttpClientTimeout {
    public static void main(String[] args) throws Exception {
        //初始化httpClient
        HttpClient httpClient = HttpClients.createDefault();
        //Get请求(Post方法相似)
        HttpGet httpGet=new HttpGet("https://searchcustomerexperience.techtarget.com/info/news");
        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2*1000).setConnectTimeout(2*1000).setConnectionRequestTimeout(10*1000).build();
        //httpGet信息配置
        httpGet.setConfig(requestConfig);
        HttpResponse response = null;
        try {
            //执行请求
            response = httpClient.execute(httpGet);
        }catch (Exception e){
            e.printStackTrace();
        }
        //获取结果
        String result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println(result);
    }
}