通过HttpClient发送请求时,需要设置请求超时时间、连接超时时间、读取数据超时时间等参数。用来避免因请求过程中等待时间太长,影响上下游交易的超时和服务器性能。
1.1设置http请求的连接超时时间-setConnectTimeout方法参数,单位毫秒(是建立连接的超时时间)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//设置http请求的连接超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).build();
//创建post请求
HttpPost httpPost = new HttpPost("http://192.168.1.123:8080/fqz");
String send = "{"a":"A","b":"BB"}";//请求的主体信息
StringEntity entity = new StringEntity(send,"utf-8");//设置post请求的拜纳姆格式
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type","application/json;charset=utf-8");//设置请求头
httpPost.setConfig(requestConfig);//设置请求参数【超时时间】
CloseableHttpResponse response = httpClient.execute(httpPost);
1.2设置http请求的读取数据超时时间-setSocketTimeout方法参数,单位毫秒(如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//设置http请求的读取数据超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).build();
//创建post请求
HttpPost httpPost = new HttpPost("http://192.168.1.123:8080/fqz");
String send = "{"a":"A","b":"BB"}";//请求的主体信息
StringEntity entity = new StringEntity(send,"utf-8");//设置post请求的拜纳姆格式
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type","application/json;charset=utf-8");//设置请求头
httpPost.setConfig(requestConfig);//设置请求参数【超时时间】
CloseableHttpResponse response = httpClient.execute(httpPost);
1.3设置http请求的超时时间- setConnectionRequestTimeout方法参数,单位毫秒(一般没有通过连接池获取连接不需要设置)
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//设置http请求的超时时间,指等待连接池中可用连接的时间,超过这个时间会抛出ConnectionPoolTimeoutException异常
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout (5000).build();
//创建post请求
HttpPost httpPost = new HttpPost("http://192.168.1.123:8080/fqz");
String send = "{"a":"A","b":"BB"}";//请求的主体信息
StringEntity entity = new StringEntity(send,"utf-8");//设置post请求的拜纳姆格式
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type","application/json;charset=utf-8");//设置请求头
httpPost.setConfig(requestConfig);//设置请求参数【超时时间】
CloseableHttpResponse response = httpClient.execute(httpPost);
1.4 设置Http请求的重试次数,参数设置setMaxRedirects方法,超过这个次数会抛出TooManyRedirectsException异常
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//设置http请求的重试次数
RequestConfig requestConfig = RequestConfig.custom().setMaxRedirect s(3).build();
//创建post请求
HttpPost httpPost = new HttpPost("http://192.168.1.123:8080/fqz");
String send = "{"a":"A","b":"BB"}";//请求的主体信息
StringEntity entity = new StringEntity(send,"utf-8");//设置post请求的拜纳姆格式
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type","application/json;charset=utf-8");//设置请求头
httpPost.setConfig(requestConfig);//设置请求参数【请求重试次数】
CloseableHttpResponse response = httpClient.execute(httpPost);