HttpClient(4.5) post get https 实例
Posted OkidoGreen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient(4.5) post get https 实例相关的知识,希望对你有一定的参考价值。
关于超时时间设置的问题:
1. connectTimeOut:指建立连接的超时时间,比较容易理解
2. connectionRequestTimeOut:指从连接池获取到连接的超时时间,如果是非连接池的话,该参数暂时没有发现有什么用处
3. socketTimeOut:指客户端和服务进行数据交互的时间,是指两者之间如果两个数据包之间的时间大于该时间则认为超时,而不是整个交互的整体时间,比如如果设置1秒超时,如果每隔0.8秒传输一次数据,传输10次,总共8秒,这样是不超时的。而如果任意两个数据包之间的时间超过了1秒,则超时。
同时,当访问不了时,会自动触发默认的重试机制3次,所以如果在需要快速响应的场景,可以重写默认的重试机制,改为0次。
参见:https://blog.csdn.net/z69183787/article/details/79010205
maven:
<httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version>
<!-- http client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>$httpclient.version</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>$httpcore.version</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>$httpclient.version</version>
</dependency>
Java:
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by Administrator on 2015/11/28.
*/
public class HttpClientUtil
private static HttpClientContext context = HttpClientContext.create();
private static RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(60000)
.setConnectionRequestTimeout(60000).setCookieSpec(CookieSpecs.STANDARD_STRICT).
setExpectContinueEnabled(true).
setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).
setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
//https
private static SSLConnectionSocketFactory socketFactory;
private static TrustManager manager = new X509TrustManager()
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException
@Override
public X509Certificate[] getAcceptedIssuers()
return null;
;
private static void enableSSL()
try
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]manager, null);
socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
catch (NoSuchAlgorithmException e)
e.printStackTrace();
catch (KeyManagementException e)
e.printStackTrace();
/**
* https get
* @param url
* @param data
* @return
* @throws java.io.IOException
*/
public static CloseableHttpResponse doHttpsGet(String url, String data)
enableSSL();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig).build();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = null;
try
response = httpClient.execute(httpGet, context);
catch (Exception e)
e.printStackTrace();
return response;
/**
* https post
* @param url
* @param values
* @return
* @throws java.io.IOException
*/
public static CloseableHttpResponse doHttpsPost(String url, List<NameValuePair> values)
enableSSL();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(url);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
try
response = httpClient.execute(httpPost, context);
catch (Exception e)
return response;
/**
* http get
*
* @param url
* @param data
* @return
*/
public static CloseableHttpResponse doGet(String url, String data)
CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = HttpClientBuilder.create().
setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).
setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultHeaders(new ArrayList<Header>()).
setDefaultCookieStore(cookieStore).
setDefaultRequestConfig(requestConfig).build();
HttpGet httpGet = new HttpGet(url);
//httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
CloseableHttpResponse response = null;
try
response = httpClient.execute(httpGet, context);
catch (Exception e)
return response;
/**
* http post
*
* @param url
* @param values
* @return
*/
public static CloseableHttpResponse doPost(String url, List<NameValuePair> values)
CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = HttpClientBuilder.create().
setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).
setRedirectStrategy(new DefaultRedirectStrategy()).
setDefaultCookieStore(cookieStore).
setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(url);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
try
response = httpClient.execute(httpPost, context);
catch (Exception e)
return response;
public static CloseableHttpResponse doJsonPost(String url,String json)
CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = HttpClientBuilder.create().
setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).
setRedirectStrategy(new DefaultRedirectStrategy()).
setDefaultCookieStore(cookieStore).
setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse httpResponse;
StringEntity entity = new StringEntity(json,"utf-8");//解决中文乱码问题
httpPost.setEntity(entity);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
httpPost.addHeader("charset", "utf-8");
CloseableHttpResponse response = null;
try
response = httpClient.execute(httpPost, context);
catch (Exception e)
return response;
/**
* 直接把Response内的Entity内容转换成String
*
* @param httpResponse
* @return
*/
public static String toString(CloseableHttpResponse httpResponse)
// 获取响应消息实体
String result = null;
try
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
result = EntityUtils.toString(entity,"UTF-8");
catch (Exception e)finally
try
httpResponse.close();
catch (IOException e)
e.printStackTrace();
return result;
public static void main(String[] args)
CloseableHttpResponse response = HttpClientUtil.doHttpsGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb2ebe42765aad029&secret=720661590f720b1f501ab3f390f80d52","");
System.out.println(HttpClientUtil.toString(response));
/**
* http post
*
* @param url
* @param values
* @return
*/
public static String doHttpPost(String url, List<NameValuePair> values)
String result = null;
CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = HttpClientBuilder.create().
setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).
setRedirectStrategy(new DefaultRedirectStrategy()).
setDefaultCookieStore(cookieStore).
setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(url);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
try
response = httpClient.execute(httpPost, context);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK)
HttpEntity resEntity = response.getEntity();
result = EntityUtils.toString(resEntity);
// 消耗掉response
EntityUtils.consume(resEntity);
catch (Exception e)
logger.info("doHttpPost",e);
finally
HttpClientUtils.closeQuietly(response);
HttpClientUtils.closeQuietly(httpClient);
return result;
https + 连接池:
http与https均可以请求及访问
import org.apache.commons.collections.MapUtils;
import org.apache.http.*;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpsUtils
private static final String HTTP = "http";
private static final String HTTPS = "https";
private static SSLConnectionSocketFactory sslsf = null;
private static PoolingHttpClientConnectionManager cm = null;
private static SSLContextBuilder builder = null;
private static HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler()
@Override
public boolean retryRequest(IOException exception,
int executionCount, HttpContext context)
return false;
;
static
try
builder = new SSLContextBuilder();
// 全部信任 不做身份鉴定
builder.loadTrustMaterial(null, new TrustStrategy()
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException
return true;
);
sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2", null, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register(HTTP, new PlainConnectionSocketFactory())
.register(HTTPS, sslsf)
.build();
cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(200);//max connection
catch (Exception e)
e.printStackTrace();
/**
* httpClient post请求
* @param url 请求url
* @param header 头部信息
* @param param 请求参数 form提交适用
* @param entity 请求实体 json/xml提交适用
* @return 可能为空 需要处理
* @throws Exception
*
*/
public static String post(String url, Map<String, String> header, Map<String, String> param, HttpEntity entity) throws Exception
String result = "";
CloseableHttpClient httpClient = null;
try
httpClient = getHttpClient();
HttpPost httpPost = new HttpPost(url);
// 设置头信息
if (MapUtils.isNotEmpty(header))
for (Map.Entry<String, String> entry : header.entrySet())
httpPost.addHeader(entry.getKey(), entry.getValue());
// 设置请求参数
if (MapUtils.isNotEmpty(param))
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : param.entrySet())
//给参数赋值
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
httpPost.setEntity(urlEncodedFormEntity);
// 设置实体 优先级高
if (entity != null)
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK)
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity);
else
readHttpResponse(httpResponse);
catch (Exception e) throw e;
finally
if (httpClient != null)
httpClient.close();
return result;
public static String get(String url, Map<String, String> header) throws Exception
String result = "";
CloseableHttpClient httpClient = null;
try
httpClient = getHttpClient();
HttpGet httpGet = new HttpGet(url);
// 设置头信息
if (MapUtils.isNotEmpty(header))
for (Map.Entry<String, String> entry : header.entrySet())
httpGet.addHeader(entry.getKey(), entry.getValue());
HttpResponse httpResponse = httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK)
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity);
else
readHttpResponse(httpResponse);
catch (Exception e) throw e;
finally
if (httpClient != null)
httpClient.close();
return result;
public static CloseableHttpClient getHttpClient() throws Exception
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(cm).setRetryHandler(myRetryHandler)
.setConnectionManagerShared(true)
.build();
return httpClient;
public static String readHttpResponse(HttpResponse httpResponse)
throws ParseException, IOException
StringBuilder builder = new StringBuilder();
// 获取响应消息实体
HttpEntity entity = httpResponse.getEntity();
// 响应状态
builder.append("status:" + httpResponse.getStatusLine());
builder.append("headers:");
HeaderIterator iterator = httpResponse.headerIterator();
while (iterator.hasNext())
builder.append("\\t" + iterator.next());
// 判断响应实体是否为空
if (entity != null)
String responseString = EntityUtils.toString(entity);
builder.append("response length:" + responseString.length());
builder.append("response content:" + responseString.replace("\\r\\n", ""));
return builder.toString();
以上是关于HttpClient(4.5) post get https 实例的主要内容,如果未能解决你的问题,请参考以下文章
HttpClient--使用HttpClient进行Get Post请求访问