httpclient 4.3新变化

    xiaoxiao2021-03-26  3

    创建httpclient不同

    CloseableHttpClient client=HttpClients.createDefault();(3.x) HttpClient client=new DefaultHttpClient(); (4.3)

    设置超时

    3.x

    HttpClient client = new HttpClient(); client.setConnectionTimeout(30000);   client.setTimeout(30000);

    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

      3.x--->4.2

    client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,2000);//连接时间

    client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,2000);//数据传输时间

    4.3

    HttpGet get=new HttpGet();//(post设置类似)

    RequestConfig config= RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).setProxy(new HttpHost("127.0.0.1", 8888)).build();//设置请求和传输超时时间已经代理

    get.setConfig(requestConfig);

    client.execute(get);//执行请求

    更一般的用法如下:

    CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig defaultRequestConfig = RequestConfig.custom() .setSocketTimeout(5000)//5秒根据实际情况更改 .setConnectTimeout(5000)//5秒根据实际情况更改 .setConnectionRequestTimeout(5000) .setStaleConnectionCheckEnabled(true)

    .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)//设置cookie策略为浏览器模式 以免出现cookie2

    .build();

    //把上面defaultRequestConfig用做客户端默认的config

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();

    Request可以覆盖客户端级别的请求配置 HttpGet httpget = new HttpGet("http://www.apache.org/"); RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)     .setProxy(new HttpHost("myotherproxy", 8080))     .build(); httpget.setConfig(requestConfig);

    cookie设置

    CookieStore cs=new BasicCookieStore(); BasicClientCookie cookie=new BasicClientCookie("cookieName", "cookieValue"); cookie.setDomain(".domain"); cookie.setPath("/"); cs.addCookie(cookie);

    只有设置了域名和路径,自定义添加的cookie才有效。

    转载请注明原文地址: https://ju.6miu.com/read-650250.html

    最新回复(0)