httpcore4.4.10, httpclient4.5.6

 package com.test.http;

 import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.client.config.RequestConfig;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.XML; import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map; public class HTTPUtils {
private static RequestConfig config; public HTTPUtils(){
config = RequestConfig.custom()
.setConnectionRequestTimeout(3000)
.setConnectTimeout(3000)
.setSocketTimeout(3000)
.build();
} /**
* 自定义超时时间
* @param connectionRequestTimeout 指从连接池获取连接的timeout
* @param connectTimeout 指客户端和服务器建立连接的timeout,超时后会ConnectionTimeOutException
* @param socketTimeout 指客户端从服务器读取数据的timeout,超出后会抛出SocketTimeOutException
*/
public HTTPUtils(int connectionRequestTimeout, int connectTimeout, int socketTimeout){
config = RequestConfig.custom()
.setConnectionRequestTimeout(connectionRequestTimeout)
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.build();
} /**
* post请求
* @param url String
* @param header String
* @param requestBody String
* @return 自定义Response
*/
public Response post(String url, String header, String requestBody) throws IOException {
CloseableHttpClient httpclient = buildSSLCloseableHttpClient(url);
HttpPost httppost = new HttpPost(url);
httppost.setConfig(config);
if (header != null && !header.equals("")) {
for (Map.Entry<String, String> entry : getRequestHeader(header).entrySet()) {
httppost.setHeader(entry.getKey(), entry.getValue());
}
}
httppost.setEntity(new StringEntity(requestBody));
CloseableHttpResponse response = httpclient.execute(httppost);
return getResponse(response);
} /**
* get请求
* @param url String
* @param header String
* @return 自定义Response
*/
public Response get(String url, String header) throws IOException {
CloseableHttpClient httpclient = buildSSLCloseableHttpClient(url);
HttpGet httpget = new HttpGet(url);
httpget.setConfig(config);
if (header != null && !header.equals("")) {
for (Map.Entry<String, String> entry : getRequestHeader(header).entrySet()) {
httpget.setHeader(entry.getKey(), entry.getValue());
}
}
CloseableHttpResponse response = httpclient.execute(httpget);
return getResponse(response);
} /**
* header格式[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"}]
* @param header String
* @return Map<String, String>
*/
private Map<String, String> getRequestHeader(String header){
Map<String, String> headerMap = new HashMap<String, String>();
JSONArray headerArray = JSONArray.parseArray(header);
for (int i=0; i<headerArray.size(); i++){
JSONObject headerObject = headerArray.getJSONObject(i);
for (String key : headerObject.keySet()){
headerMap.put(key, headerObject.getString(key));
}
}
return headerMap;
} /**
* 获取response的header
* @param headers Header[]
* @return Map<String, String>
*/
private Map<String, String> getResponseHeader(Header[] headers){
Map<String, String> headerMap = new HashMap<String, String>();
for (Header header : headers) {
headerMap.put(header.getName(), header.getValue());
}
return headerMap;
} /**
* https忽略证书
* @return CloseableHttpClient
*/
private CloseableHttpClient buildSSLCloseableHttpClient(String url) {
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) {
return true;
}
}).build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
return url.startsWith("https:") ? HttpClients.custom().setSSLSocketFactory(sslsf).build() : HttpClients.createDefault();
} /**
* 获取自定义Response
* @param response CloseableHttpResponse
* @return Response
*/
private Response getResponse(CloseableHttpResponse response){
Response res = null;
try {
String result = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
res = new Response();
res.setResponseCode(response.getStatusLine().getStatusCode());
res.setResponseHeader(getResponseHeader(response.getAllHeaders()));
res.setResponseBody(result);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return res;
} /**
* json to xml
* @param json String
* @return
*/
public String json2xml(String json) {
org.json.JSONObject jsonObj = new org.json.JSONObject(json);
return "<xml>" + XML.toString(jsonObj) + "</xml>";
} /**
* xml to json
* @param xml String
* @return
*/
public String xml2json(String xml) {
org.json.JSONObject xmlJSONObj = XML.toJSONObject(xml.replace("<xml>", "").replace("</xml>", ""));
return xmlJSONObj.toString();
} @Data
public class Response{
private int responseCode;
private Map<String, String> responseHeader;
private Object responseBody;
} }

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>Httpdemo</groupId>
<artifactId>Httpdemo</artifactId>
<version>1.0-SNAPSHOT</version> <dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency> </dependencies> </project>

最新文章

  1. Spring配置文件详解 - applicationContext.xml文件路径
  2. 详解收发不畅原因及U-Mail邮件中继解决之道
  3. 密码学初级教程(一)基本概念及DES加密算法
  4. 线段树(多维+双成段更新) UVA 11992 Fast Matrix Operations
  5. Sql Server数据的加密与解密
  6. 使用Cygwin通过ssh命令行来访问Windows8
  7. android调用系统自带的的浏览器搜索关键字
  8. Java利用jcifs集成AD域用户认证
  9. YiShop_商城系统如何做好口碑营销
  10. 用Dedecms5.7的arclist标签调用文章内容
  11. Java面向对象特征之封装
  12. [Chrome] 谷歌浏览器开启开发模式仍然无法安装油猴脚本
  13. HDU 1015(字符运算 **)
  14. MG90S 舵机 使用方法 树莓派
  15. 再谈PHP设计模式
  16. contourf和contour用法区别
  17. [py]类和实例方法/内建方法
  18. ESET NOD32 Antivirus – 免费 3个月/ 3PC
  19. Nuget出现错误怎么办?
  20. ContextMenu上下文菜单

热门文章

  1. sql 书写 规范 优化
  2. JS自动微信消息轰炸
  3. 4月10日java多线程3
  4. 【算法】—— LRU算法
  5. MD 的常用语法格式
  6. codeforces645B
  7. POJChallengeRound2 Guideposts 【单位根反演】【快速幂】
  8. [curl]convert curl to python Ruby
  9. CF24D Broken robot
  10. 第四章:条件语句(if)和循环结构(while)