首先说一下该类中需要引入的 jar 包,apache 的 httpclient 包,版本号为 4.5,如有需要的话,可以引一下。
 
 

代码

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; /**
* HTTP 请求工具类
*
* @author : liii
* @version : 1.0.0
* @date : 2015/7/21
* @see : TODO
*/
public class HttpUtil {
private static PoolingHttpClientConnectionManager connMgr;
private static RequestConfig requestConfig;
private static final int MAX_TIMEOUT = 7000; static {
// 设置连接池
connMgr = new PoolingHttpClientConnectionManager();
// 设置连接池大小
connMgr.setMaxTotal(100);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal()); RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(MAX_TIMEOUT);
// 设置读取超时
configBuilder.setSocketTimeout(MAX_TIMEOUT);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
// 在提交请求之前 测试连接是否可用
configBuilder.setStaleConnectionCheckEnabled(true);
requestConfig = configBuilder.build();
} /**
* 发送 GET 请求(HTTP),不带输入数据
* @param url
* @return
*/
public static String doGet(String url) {
return doGet(url, new HashMap<String, Object>());
} /**
* 发送 GET 请求(HTTP),K-V形式
* @param url
* @param params
* @return
*/
public static String doGet(String url, Map<String, Object> params) {
String apiUrl = url;
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : params.keySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
param.append(key).append("=").append(params.get(key));
i++;
}
apiUrl += param;
String result = null;
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpPost = new HttpGet(apiUrl);
HttpResponse response = httpclient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode(); System.out.println("执行状态码 : " + statusCode); HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
} /**
* 发送 POST 请求(HTTP),不带输入数据
* @param apiUrl
* @return
*/
public static String doPost(String apiUrl) {
return doPost(apiUrl, new HashMap<String, Object>());
} /**
* 发送 POST 请求(HTTP),K-V形式
* @param apiUrl API接口URL
* @param params 参数map
* @return
*/
public static String doPost(String apiUrl, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null; try {
httpPost.setConfig(requestConfig);
List<NameValuePair> pairList = new ArrayList<>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
response = httpClient.execute(httpPost);
System.out.println(response.toString());
HttpEntity entity = response.getEntity();
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
} /**
* 发送 POST 请求(HTTP),JSON形式
* @param apiUrl
* @param json json对象
* @return
*/
public static String doPost(String apiUrl, Object json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null; try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");//解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine().getStatusCode());
httpStr = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
} /**
* 发送 SSL POST 请求(HTTPS),K-V形式
* @param apiUrl API接口URL
* @param params 参数map
* @return
*/
public static String doPostSSL(String apiUrl, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
String httpStr = null; try {
httpPost.setConfig(requestConfig);
List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
} /**
* 发送 SSL POST 请求(HTTPS),JSON形式
* @param apiUrl API接口URL
* @param json JSON对象
* @return
*/
public static String doPostSSL(String apiUrl, Object json) {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
String httpStr = null; try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");//解决中文乱码问题
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
} /**
* 创建SSL安全连接
*
* @return
*/
private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
SSLConnectionSocketFactory sslsf = null;
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { @Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
} @Override
public void verify(String host, SSLSocket ssl) throws IOException {
} @Override
public void verify(String host, X509Certificate cert) throws SSLException {
} @Override
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
}
});
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
return sslsf;
} /**
* 测试方法
* @param args
*/
public static void main(String[] args) throws Exception { }
}

HttpClient 发送 HTTP、HTTPS的更多相关文章

  1. springboot2.X集成HttpClient 发送HTTPS 请求

    1)jar <!--httpclient 发送外部https/http 请求--> <dependency> <groupId>org.apache.httpcom ...

  2. Java实现HttpClient发送GET、POST请求(https、http)

    1.引入相关依赖包 jar包下载:httpcore4.5.5.jar    fastjson-1.2.47.jar maven: <dependency> <groupId>o ...

  3. 【JAVA】通过HttpClient发送HTTP请求的方法

    HttpClient介绍 HttpClient 不是一个浏览器.它是一个客户端的 HTTP 通信实现库.HttpClient的目标是发 送和接收HTTP 报文.HttpClient不会去缓存内容,执行 ...

  4. 接口测试——HttpClient工具的https请求、代理设置、请求头设置、获取状态码和响应头

    目录 https请求 代理设置 请求头设置 获取状态码 接收响应头 https请求 https协议(Secure Hypertext Transfer Protocol) : 安全超文本传输协议, H ...

  5. .net core使用HttpClient发送代理请求_程序内抓包_Fiddler抓包

    前言:  通过Fiddler抓取浏览器请求数据,相信大家已经都会用了,我们知道Fiddler是通过在本机计算器添加一个默认的代理服务器来实现的抓包数据的,端口号为:8888. 其实当我们打开Fiddl ...

  6. Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)

    ​[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...

  7. Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据)

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  8. httpclient发送multipart/form-data类型参数和用MultipartRequest接收参数

    一.利用HttpClient发送基于Content-Type="multipart/form-data"形式的表单 package com.test.httpclient; imp ...

  9. 使用HttpClient发送请求、接收响应

    使用HttpClient发送请求.接收响应很简单,只要如下几步即可. 1.创建HttpClient对象.  CloseableHttpClient httpclient = HttpClients.c ...

  10. (一)----使用HttpClient发送HTTP请求(通过get方法获取数据)

    (一)----使用HttpClient发送HTTP请求(通过get方法获取数据) 一.HTTP协议初探: HTTP(Hypertext Transfer Protocol)中文 “超文本传输协议”,是 ...

随机推荐

  1. winform截屏

    引自 http://www.cnblogs.com/aland-liu/archive/2011/07/20/Winform.html 已经注册博客好久,一直由于工作原因没有打理.今天在网上看了一个截 ...

  2. Eclipse: the import java.util cannot be resolved

    the import java.util cannot be resolved 导入JRE System Library. 右键项目 Build Path Configure Build Path.. ...

  3. springMVC学习(4)-商品修改(RequestMapping解释、controller返回值)

    一.需求: 操作流程: 1.进入商品查询列表页面 2.点击修改,进入商品修改页面,页面中显示了要修改的商品(从数据库查询) 3.在商品修改页面,修改商品信息,修改后,点击提交 代码: ItemsMap ...

  4. linux nfs怪现象——软连接、文件属主的变更

    怪现象:proxmox:/etc-asterisk# ls sip.confsip.confproxmox:/etc-asterisk# more sip.confsip.conf: No such ...

  5. 服务器开启JMX监控

    JMX是一个框架,提供了一种功能,可以实时查询应用程序中通过JMX向外部公布的相应参数或者是其他应用程序,同时也可以通过JMX来实时地调用应用程序使用JMX向外部公布的接口,来完成一些功能操作. 如果 ...

  6. 理解 tornado.gen

    转自:http://blog.xiaogaozi.org/2012/09/21/understanding-tornado-dot-gen/ 理解 tornado.gen SEP 21ST, 2012 ...

  7. 《Linux内核精髓:精通Linux内核必会的75个绝技》一HACK #15 ramzswap

    HACK #15 ramzswap 本节介绍将一部分内存作为交换设备使用的ramzswap.ramzswap是将一部分内存空间作为交换设备使用的基于RAM的块设备.对要换出(swapout)的页面进行 ...

  8. 编写函数digit(num, k),函数功能是:求整数num从右边开始的第k位数字的值,如果num位数不足k位则返回0。

    function digit(num,k){         var knum = 0;         for(var i=1; i<=k; i++){                 knu ...

  9. opencv小问题大智慧

    opencv易错点记录 1. 判断条件不应使用CV_ASSERT(),而使用CV_Assert(). 2.  用下面这个自适应阈值必须进行数据的转换,不能直接传入数据!不然程序一直崩溃,找了很久才发现 ...

  10. 网络性能测试工具iperf

    参考网站:https://www.cnblogs.com/yingsong/p/5682080.html https://docs.azure.cn/zh-cn/articles/azure-oper ...