httpclient 相关使用介绍

httpclient中sessionId的获取与设置

public class HttpSessionId {
    public static void main(String[] args) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        String urlStr = "http://baidu.com";
        HttpPost post = new HttpPost(urlStr);
        HttpResponse response = client.execute(post);


        StatusLine statusLine = response.getStatusLine();
        String respon = null;
        int statuscode = statusLine.getStatusCode();
        if (statuscode == 200) {
            CookieStore cookieStore = ((AbstractHttpClient) client).getCookieStore();
            List<Cookie> cookies = cookieStore.getCookies();
            for (Cookie ck : cookies) {
                if ("JESSIONID".equals(ck.getName())) {
                    String sessionId = ck.getValue();
                    break;
                }
            }
        }
    }
}

hc_post参数

json串形式StringEntity

StringEntity stringEntity = new StringEntity(tojson.toJson());
stringEntity.setContentType("text/json");
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
httpPost.setEntity(entity);

参数形式HttpEntity

List<NameValuePair> params = new ArrayList<>();
params.add(new NameValuePair("name","ssgao"));
params.add(new NameValuePair("age","30"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,"utf-8");
HttpPost post = new HttpPost("http://127.0.0.1/handle.do");
post.setEntity(entity);

上传文件MultiPartEntity

MultipartEntity entity = new MultipartEntity();
entity.addPart("param1",new StringBody("ssgao",Charset.forName("utf-8")));
entity.addPart("param2",new StringBody("shuoailin",Charset.forName("utf-8")));
entity.addPart("param3",new FileBody(new File("c:1.txt"))));
request.setEntity(entity);

httpclient超时时间设置

***httpclient内部有三个超时时间设置 ***

连接池获取可用连接超时
连接超时
读取数据超时
 
不设置超时时间
如果不设置超时时间一旦服务器无响应的情况,如果返回404,50x错误还好,如果没有没有返回,java线程会一直阻塞等待
public class HttpTimeDemo {
    public static void main(String[] args) {
        RequestConfig requestConfig = RequestConfig.custom()
                        .setConnectionRequestTimeout(1000) //从连接池中获取连接的超时时间
                        .setConnectTimeout(1000) //与服务器连接超时时间,httpclient会创建一个异步线程用以创建socket连接
                        .setSocketTimeout(1000) //socket读取数据超时时间,从服务器获取响应数据的超时时间
                        .build();
        CloseableHttpClient httpClient = HttpClientBuilder.create()
                        .setMaxConnTotal(100) //连接池中最大连接数
                        .setMaxConnPerRoute(50) //分配给同一个route(路由)最大的并发连接数
                        .setDefaultRequestConfig(requestConfig)
                        .build();
        /**
         * route: 运行环境机器 到 目标机器的一条线路
         * 举例: 我们使用httpclient来分别请求 www.baidu.com的资源和 www.bing.com的资源,那么它就会产生两个route
         */
    }
}

使用httpParam设置超时时间

HttpClient httpclient = new  DefaultHttpClient();
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,  Config.20000);//连接时间20s
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,  60000);//数据传输时间60s
 
链接超时
httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(60000);
读取超时
httpClient.getHttpConnectionManager().getParams().setSoTimeot(60000)

三个超时时间详解

'从连接池中获取可用连接超时'
httpclient中的要用连接时尝试从连接池中获取,若是在等待了一定时间后还没有获取到可用连接(比如连接池中没有空闲连接)
'连接目标超时connectionTimeout'
指的是连接目标url的连接超时时间,即客户端发送请求到目标url建立连接的最大时间。
如果在该时间范围内还没有建立连接,抛出异常
'等待响应超时(读取超时)socketTimeout'
连接上一个url后,获取response的返回等待时间,即在于目标url建立连接后,等待放回response的最大时间,在规定时间没有
返回响应的话就抛出SocketTimeout

测试sockettimeout
本地开启一个url http://localhost:8080/firstTime?method=test
这个测试url中,当访问这个链接时,线程sleep一段时间,来模拟返回response时间
@RequestMapping(params = "method=test")  
public String testMethod(ModelMap model) {      
 try {      
    Thread.sleep(10000);      
 } catch (InterruptedException e) {      
    e.printStackTrace();      
 }      
 System.out.println("call testMethod method.");      
 model.addAttribute("name", "test method");      
 return "test";      
}  

将读取response返回超时时间设的时间比那个sleep时间短之后,运行程序给出异常
java.net.SocketTimeoutException:Read timed out
原文地址:https://www.cnblogs.com/ssgao/p/8829192.html