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>

Java+maven+httpcomponents封装post/get请求的更多相关文章

  1. 【SpringBoot】 Java中如何封装Http请求,以及JSON多层嵌套解析

    前言 本文中的内容其实严格来说不算springboot里面的特性,属于JAVA基础,只是我在项目中遇到了,特归纳总结一下. HTTP请求封装 目前JAVA对于HTTP封装主要有三种方式: 1. JAV ...

  2. java + maven 实现发送短信验证码功能

    如何使用java + maven的项目环境发送短信验证码,本文使用的是榛子云短信 的接口. 1. 安装sdk 下载地址: http://smsow.zhenzikj.com/doc/sdk.html ...

  3. Java基础/发起http和https请求

    Java中发起http和https请求 一般调用外部接口会需要用到http和https请求. 本案例为:前后端完全分离,前端框架(React+Mobx+Nornj),后端(Go语言). 面临问题:跨域 ...

  4. 封装的ajax请求

    在做登录注册这类提交表单数据时,我们经常需要局部刷新网页来验证用户输入的信息,这就需要用到ajax请求,我们通常需要获取表单中的数据,发起ajax请求,通过服务程序,与数据库的数据进行比对,判断信息的 ...

  5. Java数据库连接池封装与用法

    Java数据库连接池封装与用法 修改于抄袭版本,那货写的有点BUG,两个类,一个用法 ConnectionPool类: package com.vl.sql; import java.sql.Conn ...

  6. Android 网络请求库volley的封装,让请求更方便

    首先封装一下volley 请求 public class CustomRequest extends StringRequest { private static final String TAG = ...

  7. Java—继承、封装、抽象、多态

    类.对象和包 1) 面向对象编程(Object Oriented Programming ,简称 OOP):20世纪70年代以后开始流行. 2) 结构化编程与面向对象编程的区别: A. 在结构化编程中 ...

  8. Java中的封装

    在前面的一些日子里,一只都在学习C#语言,使用C#在做一些小项目的,今天转到了Java的学习,还是感觉有点的不习惯,没有以前的中文界面的,全是英文.写起代码来都一直保持着C#中的编码的习惯,但是学习J ...

  9. JAVA基础知识之网络编程——-网络基础(Java的http get和post请求,多线程下载)

    本文主要介绍java.net下为网络编程提供的一些基础包,InetAddress代表一个IP协议对象,可以用来获取IP地址,Host name之类的信息.URL和URLConnect可以用来访问web ...

随机推荐

  1. MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

    ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '你的密码';

  2. Python——Socket编程

    一.TCP 1.客户端 import socket sk = socket.socket() # 买个手机 sk.connect(('127.0.0.1',8080)) # 拨号 ret = sk.r ...

  3. VMware Workstation 12 Pro安装CentOs图文教程(超级详细)

    本文记录了VMware Workstation 12 Pro安装CentOs的整个过程,具体如下: VMware Workstation 12: CENTOS 6.4 : 创建虚拟机 1.首先安装好V ...

  4. Codeforces Round #542 [Alex Lopashev Thanks-Round] (Div. 2)

    A. Be Positive 题意:给出一个数组 每个树去除以d(d!=0)使得数组中大于0的数 大于ceil(n/2) 求任意d 思路:数据小 直接暴力就完事了 #include<bits/s ...

  5. CF24D Broken robot

    题目链接 题意 有一个\(n \times m\)的矩阵.机器人从点\((x,y)\)开始等概率的往下,往右,往左走或者不动.如果再第一列,那么不会往左走,再第m列不会往右走.也就是说机器人不会走出这 ...

  6. usb输入子系统写程序(三)

    目录 usb输入子系统写程序 小结 内核修改 怎么写代码 类型匹配 probe disconnect 程序设计 1th匹配probe 2th 获取usb数据 3th 输入子系统上报按键 title: ...

  7. 【.net】ASP.Net设置和取消设置web项目起始页

    #在visual studio中设置和取消web项目的起始页 方法一:在所要设置的页面上右键->设为起始页 方法二:web项目上右键->属性页 website项目: tips:如果取消要取 ...

  8. crm 动态一级二级菜单

    之前代码菜单是写是的 如何 让他 动态 生成了  首先 添加 2个字段 admin.py 更改 显示 from django.contrib import admin from rbac import ...

  9. JS异步加载的三种方案

    js加载的缺点:加载工具方法没必要阻塞文档,个别js加载会影响页面效率,一旦网速不好,那么整个网站将等待js加载而不进行后续渲染等工作. 有些工具方法需要按需加载,用到再加载,不用不加载. 一.def ...

  10. html - 表单form

    一.表单 功能:表单用于向服务器传输数据,从而实现用户与Web服务器的交互 表单能够包含input系列标签,比如文本字段.复选框.单选框.提交按钮等等. 表单还可以包含textarea.select. ...