HttpUtil工具类,发送Get/Post请求,支持Http和Https协议

使用用Httpclient封装的HttpUtil工具类,发送Get/Post请求

1. maven引入httpclient依赖

  <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>

2. GET请求

public static String doGet(String path, Map<String, String> param, Map<String, String> headers) {
HttpGet httpGet = null;
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = wrapClient(path);
// 创建uri
URIBuilder builder = null;
try {
builder = new URIBuilder(path);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
httpGet = new HttpGet(uri);
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
} // 执行请求
response = httpClient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
throw new RuntimeException("[发送Get请求错误:]" + e.getMessage());
} finally {
try {
httpGet.releaseConnection();
response.close();
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

3. POST请求

public static String doPostJson(String url, String jsonParam, Map<String, String> headers) {
HttpPost httpPost = null;
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = wrapClient(url);
try {
httpPost = new HttpPost(url);
//addHeader,如果Header没有定义则添加,已定义则不变,setHeader会重新赋值
httpPost.addHeader("Content-type","application/json;charset=utf-8");
httpPost.setHeader("Accept", "application/json");
StringEntity entity = new StringEntity(jsonParam, StandardCharsets.UTF_8);
// entity.setContentType("text/json");
// entity.setContentEncoding(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
httpPost.setEntity(entity);
//是否有header
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
// 执行请求
response = httpClient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
} } catch (Exception e) {
throw new RuntimeException("[发送POST请求错误:]" + e.getMessage());
} finally {
try {
httpPost.releaseConnection();
response.close();
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

3. 获取httpclient的方法

这里会根据url自动匹配需要的是http的还是https的client

  private static CloseableHttpClient wrapClient(String url) {
CloseableHttpClient client = HttpClientBuilder.create().build();
if (url.startsWith("https")) {
client = getCloseableHttpsClients();
}
return client;
}

4. 对于https的需要自己实现一下client

private static CloseableHttpClient getCloseableHttpsClients() {
// 采用绕过验证的方式处理https请求
SSLContext sslcontext = createIgnoreVerifySSL();
// 设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext)).build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
// 创建自定义的httpsclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
return client;
}
private static SSLContext createIgnoreVerifySSL() {
// 创建套接字对象
SSLContext sslContext = null;
try {
//指定TLS版本
sslContext = SSLContext.getInstance("TLSv1.2");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("[创建套接字失败:] " + e.getMessage());
}
// 实现X509TrustManager接口,用于绕过验证
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
} @Override
public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
} @Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
try {
//初始化sslContext对象
sslContext.init(null, new TrustManager[]{trustManager}, null);
} catch (KeyManagementException e) {
throw new RuntimeException("[初始化套接字失败:] " + e.getMessage());
}
return sslContext;
}

以上全部都测试通过,如果有错误,欢迎大佬们指出,感谢!!!

备注:完整版的点这里

让坚持成为品质,让优秀成为习惯!加油!

HttpUtil工具类,发送Get/Post请求,支持Http和Https协议的更多相关文章

  1. HttpUtil工具类

    HttpUtil工具类 /** * 向指定URL发送GET方法的请求 * * @param url * 发送请求的URL * @param params * 请求参数,请求参数应该是name1=val ...

  2. 牛客网Java刷题知识点之UDP协议是否支持HTTP和HTTPS协议?为什么?TCP协议支持吗?

    不多说,直接上干货! 福利 => 每天都推送 欢迎大家,关注微信扫码并加入我的4个微信公众号:   大数据躺过的坑      Java从入门到架构师      人工智能躺过的坑          ...

  3. Spring Boot项目如何同时支持HTTP和HTTPS协议

    如今,企业级应用程序的常见场景是同时支持HTTP和HTTPS两种协议,这篇文章考虑如何让Spring Boot应用程序同时支持HTTP和HTTPS两种协议. 准备 为了使用HTTPS连接器,需要生成一 ...

  4. 通过Httpclient工具类,实现接口请求

    package luckyweb.seagull.util; import org.apache.http.NameValuePair; import org.apache.http.client.e ...

  5. httpclient4.5.2 Post请求支持http和https

    先导入所需的jar包,pom.xml <dependency> <groupId>org.springframework.boot</groupId> <ar ...

  6. 工具类: 用于模拟HTTP请求中GET/POST方式

    package com.jarvis.base.util; import java.io.BufferedReader; import java.io.IOException; import java ...

  7. 工具类总结---(六)---之http及https请求

    下面使用的是HttpURLConnection进行的网络链接,并对https进行了忽略证书. 在这个utils里面,也使用到前面几个utils,比如下载文件的方法,就使用到了Fileutils pac ...

  8. 自己写的Android端HttpUtil工具类

    package com.sxt.jcjd.util; import java.io.IOException; import java.io.UnsupportedEncodingException; ...

  9. HttpClientUtil 工具类 实现跨域请求数据

    package com.xxx.common.util; import java.io.IOException; import java.net.URI; import java.util.Array ...

随机推荐

  1. 导出word excel 方法

    ---导出excel public static void DataTableToExcelXjd(DataTable dt, string Title, string TmpColsName) { ...

  2. asp中设置session过期时间方法总结

    http://www.jb51.net/article/31217.htm asp中设置session过期时间方法总结 作者: 字体:[增加 减小] 类型:转载   asp中默认session过期时间 ...

  3. poj2823单调队列认知

    Sliding Window Time Limit: 12000MS   Memory Limit: 65536K Total Submissions: 62930   Accepted: 17963 ...

  4. 最小比率树 poj2728

    以下内容均为转载 http://www.cnblogs.com/ftae/p/6947497.html poj2728(最小比率生成树)   poj2728 题意 给出 n 个点的坐标和它的高度,求一 ...

  5. 25-12 空值处理(null值)

    --------------------空值处理--------------------- select * from TblStudent --查询所有年龄是null的同学学习信息 --null值无 ...

  6. Java——倒序输出Map集合

    package com.java.test.a; import java.util.ArrayList; import java.util.LinkedHashMap; import java.uti ...

  7. Element Form表单实践(下)

    作者:小土豆biubiubiu 博客园:https://www.cnblogs.com/HouJiao/ 掘金:https://juejin.im/user/58c61b4361ff4b005d9e8 ...

  8. Java——MVC模式

    MVC:Model View Controller 一般用于动态程序设计,实现了业务逻辑和表示层分离 Model:掌控数据源-->程序员编写程序或者实现算法,数据库人员进行数据库操作等:响应用户 ...

  9. [SD心灵鸡汤]002.每月一则 - 2015.06

    1.用最多的梦面对未来 2.自己要先看得起自己,别人才会看得起你 3.一个今天胜过两个明天 4.要铭记在心:每天都是一年中最美好的日子 5.乐观者在灾祸中看到机会:悲观者在机会中看到灾祸 6.有勇气并 ...

  10. Unity 离线建造系统

    很多游戏,特别是养成类手游,都会有自己独特的建造系统,一个建造装置的状态循环或者说生命周期一般是这样的: 1.准备建造,设置各项资源的投入等 2.等待一段倒计时,正在建造中 3.建造结束,选择是否收取 ...