不多说直接上代码,你们就去研究去吧
工具类:
package com.zzdz.performance.infra;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.*;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.*;
/**
* <p>
* HttpClientUtil<br>
* http请求工具类(注意编码格式会带来请求错误,如201)
* </p>
*
* @author XinLau
* @version 1.0
* @since 2019年08月30日 10:04
*/
public class HttpClientUtil {
/**
* 编码格式
*/
private static final String UTF_8 = "utf-8";
/**
* CloseableHttpClient
*/
private static CloseableHttpClient closeableHttpClient = null;
/**
* HttpPost
*/
private static HttpPost httpPost = null;
/**
* HttpGet
*/
private static HttpGet httpGet = null;
/**
* HttpDelete
*/
private static HttpDelete httpDelete = null;
/**
* CloseableHttpResponse
*/
private static CloseableHttpResponse closeableHttpResponse = null;
/**
* @description 获取CloseableHttpClient 对象
* @return CloseableHttpClient
* @author XinLau
* @since 2019/9/7 13:58
* @creed The only constant is change ! ! !
*/
private static CloseableHttpClient getCloseableHttpClient(){
// HttpClients.createDefault() 等价于 HttpClientBuilder.create().build();
return HttpClientBuilder.create().build();
}
/**
* @description CloseableHttpClient 对象
* @author XinLau
* @since 2019/9/7 14:23
* @creed The only constant is change ! ! !
*/
private static void doCloseableHttpClient(){
try {
// 关闭连接、释放资源
if(closeableHttpClient != null){
closeableHttpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @description 获取 HttpPost对象
* @param url - 访问地址
* @return HttpPost
* @author XinLau
* @since 2019/9/7 13:59
* @creed The only constant is change ! ! !
*/
private static HttpPost getHttpPost(String url){
HttpPost httpPost = new HttpPost(url);
httpPost.setProtocolVersion(HttpVersion.HTTP_1_0);
return httpPost;
}
/**
* @description 获取 CloseableHttpResponse对象
* @param closeableHttpClient -
* @param httpPost -
* @return CloseableHttpResponse
* @author XinLau
* @since 2019/9/7 14:00
* @creed The only constant is change ! ! !
*/
private static CloseableHttpResponse getCloseableHttpResponse(CloseableHttpClient closeableHttpClient, HttpPost httpPost){
try {
closeableHttpResponse = closeableHttpClient.execute(httpPost);
} catch (Exception e) {
e.printStackTrace();
}
return closeableHttpResponse;
}
/**
* @description 关闭CloseableHttpResponse 对象
* @author XinLau
* @since 2019/9/7 14:23
* @creed The only constant is change ! ! !
*/
private static void doCloseableHttpResponse(){
try {
// 关闭
if(closeableHttpResponse != null){
closeableHttpResponse.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @description 关闭请求
* @author XinLau
* @since 2019/9/7 14:23
* @creed The only constant is change ! ! !
*/
public static void doHttpPostClose(){
// 关闭资源
doCloseableHttpResponse();
doCloseableHttpClient();
}
/**
* @description: 发送http get请求
* @param url - 访问地址
* @param headers - 头
* @param encode - 编码格式
* @return: CloseableHttpResponse
* @author: XinLau
* @since: 2019/8/31 10:33
* @creed: The only constant is change ! ! !
*/
public static CloseableHttpResponse httpGet(String url, Map<String, String> headers, String encode) {
if (encode == null) {
encode = "utf-8";
}
// closeableHttpClient
closeableHttpClient = getCloseableHttpClient();
// httpGet
httpGet = new HttpGet(url);
// 设置header
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
}
try {
// CloseableHttpResponse
closeableHttpResponse = closeableHttpClient.execute(httpGet);
} catch (IOException e) {
e.printStackTrace();
}
// 返回
return closeableHttpResponse;
}
/**
* @description: 发送http delete请求
* @param url - 访问地址
* @param headers - 头
* @param encode - 编码格式
* @return: HttpResponse
* @author: XinLau
* @since: 2019/8/31 10:33
* @creed: The only constant is change ! ! !
*/
public static CloseableHttpResponse httpDelete(String url, Map<String, String> headers, String encode) {
if (encode == null) {
encode = "utf-8";
}
// closeableHttpClient
closeableHttpClient = getCloseableHttpClient();
// httpDelete
httpDelete = new HttpDelete(url);
// 设置header
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
}
try {
// CloseableHttpResponse
closeableHttpResponse = closeableHttpClient.execute(httpDelete);
} catch (IOException e) {
e.printStackTrace();
}
// 返回
return closeableHttpResponse;
}
/**
* @description 发送 http post 请求,参数以form表单键值对的形式提交。
* @param url - 访问地址
* @param params - 参数
* @param headers - 头
* @param encode - 编码格式
* @return CloseableHttpResponse
* @author XinLau
* @since 2019/8/31 10:33
* @creed The only constant is change ! ! !
*/
public static CloseableHttpResponse httpPostForm(String url, Map<String, String> params, Map<String, String> headers, String encode) {
if (encode == null) {
encode = "utf-8";
}
// closeableHttpClient
closeableHttpClient = getCloseableHttpClient();
// httpPost
httpPost = getHttpPost(url);
// 设置header
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
// 组织请求参数
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
if (params != null && params.size() > 0) {
Set<String> keySet = params.keySet();
for (String key : keySet) {
paramList.add(new BasicNameValuePair(key, params.get(key)));
}
}
// 设置请求参数
try {
httpPost.setEntity(new UrlEncodedFormEntity(paramList, encode));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// CloseableHttpResponse
closeableHttpResponse = getCloseableHttpResponse(closeableHttpClient, httpPost);
// 返回
return closeableHttpResponse;
}
/**
* @description 发送 http post 请求,支持多文件上传
* @param url - 访问地址
* @param params - 参数
* @param filesList - 多文件
* @param headers - 头
* @param encode - 编码格式
* @return CloseableHttpResponse
* @author XinLau
* @since 2019/8/31 10:33
* @creed The only constant is change ! ! !
*/
public static CloseableHttpResponse httpPostFormMultipart(String url, Map<String, String> params, List<File> filesList, Map<String, String> headers, String encode) {
if (encode == null) {
encode = "utf-8";
}
// closeableHttpClient
closeableHttpClient = getCloseableHttpClient();
// httpPost
httpPost = getHttpPost(url);
/**
* 设置header
*/
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
mEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mEntityBuilder.setCharset(Charset.forName(encode));
/**
* 普通参数
*/
// 解决中文乱码
ContentType contentType = ContentType.create("text/plain", Charset.forName(encode));
if (params != null && params.size() > 0) {
Set<String> keySet = params.keySet();
for (String key : keySet) {
mEntityBuilder.addTextBody(key, params.get(key), contentType);
}
}
/**
* 二进制参数
*/
if (filesList != null && filesList.size() > 0) {
for (File file : filesList) {
mEntityBuilder.addBinaryBody("file", file);
}
}
// 设置请求参数
httpPost.setEntity(mEntityBuilder.build());
// CloseableHttpResponse
closeableHttpResponse = getCloseableHttpResponse(closeableHttpClient, httpPost);
// 返回值
return closeableHttpResponse;
}
/**
* @description 发送Http-Get请求
* @param url - 访问地址
* @return HttpResponse
* @author XinLau
* @since 2019/9/5 17:24
* @creed The only constant is change ! ! !
*/
public static HttpResponse doHttpGet(String url) {
HttpResponse response = new HttpResponse();
// 请求头
Map<String, String> headers = new HashMap<String, String>();
// 发送请求
CloseableHttpResponse closeableHttpResponse = httpGet(url, headers, UTF_8);
JSONObject jsonObject = new JSONObject();
if(closeableHttpResponse != null){
try {
// 获取响应得body部分
HttpEntity entity = closeableHttpResponse.getEntity();
String content = EntityUtils.toString(entity, UTF_8);
jsonObject = JSONObject.parseObject(content);
response.setHeaders(closeableHttpResponse.getAllHeaders());
response.setReasonPhrase(closeableHttpResponse.getStatusLine().getReasonPhrase());
// 获取响应状态码
int setHttpStatusCode = closeableHttpResponse.getStatusLine().getStatusCode();
response.setHttpStatusCode(setHttpStatusCode);
boolean httpStatusCode = setHttpStatusCode == 200;
boolean hasErrors = !jsonObject.getBooleanValue("hasErrors");
int statusCode = (hasErrors == httpStatusCode) ? 1 : 0;
response.setStatusCode(statusCode);
} catch (IOException e) {
response.setReasonPhrase("获取参数异常");
response.setStatusCode(0);
}
}else {
response.setReasonPhrase("网络连接失败");
response.setStatusCode(0);
}
response.setBody(jsonObject);
// 关闭资源
doCloseableHttpResponse();
doCloseableHttpClient();
// 返回值
return response;
}
/**
* @description 发送Http-Delete请求
* @param url - 访问地址
* @return HttpResponse
* @author XinLau
* @since 2019/9/5 17:24
* @creed The only constant is change ! ! !
*/
public static HttpResponse doHttpDelete(String url) {
HttpResponse response = new HttpResponse();
// 请求头
Map<String, String> headers = new HashMap<String, String>();
// 发送请求
CloseableHttpResponse closeableHttpResponse = httpDelete(url, headers, UTF_8);
JSONObject jsonObject = new JSONObject();
if(closeableHttpResponse != null){
try {
// 获取响应得body部分
HttpEntity entity = closeableHttpResponse.getEntity();
String content = EntityUtils.toString(entity, UTF_8);
jsonObject = JSONObject.parseObject(content);
response.setHeaders(closeableHttpResponse.getAllHeaders());
response.setReasonPhrase(closeableHttpResponse.getStatusLine().getReasonPhrase());
// 获取响应状态码
int setHttpStatusCode = closeableHttpResponse.getStatusLine().getStatusCode();
response.setHttpStatusCode(setHttpStatusCode);
boolean httpStatusCode = setHttpStatusCode == 200;
boolean hasErrors = !jsonObject.getBooleanValue("hasErrors");
int statusCode = (hasErrors == httpStatusCode) ? 1 : 0;
response.setStatusCode(statusCode);
} catch (IOException e) {
response.setReasonPhrase("获取参数异常");
response.setStatusCode(0);
}
}else {
response.setReasonPhrase("网络连接失败");
response.setStatusCode(0);
}
response.setBody(jsonObject);
// 关闭资源
doCloseableHttpResponse();
doCloseableHttpClient();
// 返回值
return response;
}
/**
* @description 发送Http-Post请求
* @param url - 访问地址
* @param params - 参数
* @return HttpResponse
* @author XinLau
* @since 2019/9/5 17:24
* @creed The only constant is change ! ! !
*/
public static HttpResponse doHttpPostForm(String url, Map<String, String> params) {
HttpResponse response = new HttpResponse();
// 请求头
Map<String, String> headers = new HashMap<String, String>();
// 发送请求
CloseableHttpResponse closeableHttpResponse = httpPostForm(url, params, headers, UTF_8);
JSONObject jsonObject = new JSONObject();
if(closeableHttpResponse != null){
try {
// 获取响应得body部分
HttpEntity entity = closeableHttpResponse.getEntity();
String content = EntityUtils.toString(entity, UTF_8);
jsonObject = JSONObject.parseObject(content);
response.setHeaders(closeableHttpResponse.getAllHeaders());
response.setReasonPhrase(closeableHttpResponse.getStatusLine().getReasonPhrase());
// 获取响应状态码
int setHttpStatusCode = closeableHttpResponse.getStatusLine().getStatusCode();
response.setHttpStatusCode(setHttpStatusCode);
boolean httpStatusCode = setHttpStatusCode == 200;
boolean hasErrors = !jsonObject.getBooleanValue("hasErrors");
int statusCode = (hasErrors == httpStatusCode) ? 1 : 0;
response.setStatusCode(statusCode);
} catch (IOException e) {
response.setReasonPhrase("获取参数异常");
response.setStatusCode(0);
}
}else {
response.setReasonPhrase("网络连接失败");
response.setStatusCode(0);
}
response.setBody(jsonObject);
// 关闭资源
doCloseableHttpResponse();
doCloseableHttpClient();
// 返回值
return response;
}
/**
* @description 发送Http-Post请求(支持多文件上传)
* @param url - 访问地址
* @param params - 参数
* @param filesList - 多文件
* @return HttpResponse
* @author XinLau
* @since 2019/9/5 17:28
* @creed The only constant is change ! ! !
*/
public static HttpResponse doHttpPostFormMultipart(String url, Map<String, String> params, List<File> filesList){
HttpResponse response = new HttpResponse();
Map<String, String> headers = new HashMap<String, String>();
// 发送请求
CloseableHttpResponse closeableHttpResponse = httpPostFormMultipart(url, params, filesList, headers, UTF_8);
JSONObject jsonObject = new JSONObject();
if(closeableHttpResponse != null){
try {
// 获取响应得body部分
HttpEntity entity = closeableHttpResponse.getEntity();
String content = EntityUtils.toString(entity, UTF_8);
jsonObject = JSONObject.parseObject(content);
response.setHeaders(closeableHttpResponse.getAllHeaders());
response.setReasonPhrase(closeableHttpResponse.getStatusLine().getReasonPhrase());
// 获取响应状态码
int setHttpStatusCode = closeableHttpResponse.getStatusLine().getStatusCode();
response.setHttpStatusCode(setHttpStatusCode);
boolean httpStatusCode = setHttpStatusCode == 200;
boolean hasErrors = !jsonObject.getBooleanValue("hasErrors");
int statusCode = (hasErrors == httpStatusCode) ? 1 : 0;
response.setStatusCode(statusCode);
} catch (Exception e) {
response.setReasonPhrase("获取参数异常");
response.setStatusCode(0);
}
}else {
response.setReasonPhrase("网络连接失败");
response.setStatusCode(0);
}
response.setBody(jsonObject);
// 关闭资源
doCloseableHttpResponse();
doCloseableHttpClient();
// 返回值
return response;
}
/**
* @description 实体类对象转Map
* @param obj - 实体类对象
* @return Map<String, Object>
* @author XinLau
* @since 2019/9/7 15:22
* @creed The only constant is change ! ! !
*/
public static Map<String, Object> convertBeanToMap(Object obj) {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// 过滤class属性
if (!key.equals("class")) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
if(null == value){
map.put(key,"");
}else{
map.put(key, value);
}
}
}
} catch (Exception e) {
}
return map;
}
/**
* @description 读取网络文件
* @param urlPath - 文件网络地址
* @param downloadDir - 文件本地存放那个地址
* @return File
* @author XinLau
* @since 2019/9/7 15:22
* @creed The only constant is change ! ! !
*/
private static File networkDownloadFile(String urlPath, String downloadDir) {
File file = null;
try {
// 统一资源
URL url = new URL(urlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
//设置超时
httpURLConnection.setConnectTimeout(1000 * 5);
//设置请求方式,默认是GET
// httpURLConnection.setRequestMethod("POST");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
// 文件大小
int fileLength = httpURLConnection.getContentLength();
// 控制台打印文件大小
//System.out.println("您要下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");
// 建立链接从请求中获取数据
URLConnection con = url.openConnection();
BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
// 指定文件名和后缀(从路径中截取)
String fileNameAndType = urlPath.substring(urlPath.lastIndexOf("/"));
// 指定存放位置(有需求可以自定义)
String path = downloadDir + File.separatorChar + fileNameAndType;
file = new File(path);
// 校验文件夹目录是否存在,不存在就创建一个目录
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file);
int size = 0;
int len = 0;
byte[] buf = new byte[2048];
while ((size = bin.read(buf)) != -1) {
len += size;
out.write(buf, 0, size);
// 控制台打印文件下载的百分比情况
//System.out.println("下载了-------> " + len * 100 / fileLength + "%\n");
}
// 关闭资源
bin.close();
out.close();
System.out.println("文件下载成功!");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("文件下载失败!");
} finally {
return file;
}
}
/**
* @description 读取多个网络文件
* @param urlPathArray - 多个文件网络地址
* @param downloadDir - 文件本地存放那个地址
* @return File
* @author XinLau
* @since 2019/9/7 15:22
* @creed The only constant is change ! ! !
*/
public static List<File> networkDownloadFileList(String[] urlPathArray, String downloadDir){
List<File> fileList = new ArrayList<File>(urlPathArray.length);
for (String urlPath : urlPathArray) {
String url = "ip:端口";
File file = networkDownloadFile(url + urlPath, downloadDir);
System.out.println(file.getName() + "是一个文件吗? " + file.isFile() + " 该文件文件大小:" + file.length() + " 全路径:" + file.getAbsolutePath() + " 存放路径:" + file.getParent());
fileList.add(file);
}
return fileList;
}
/**
* @description 删除多个本地文件
* @param filesList - 多个本地文件
* @author XinLau
* @since 2019/9/7 15:22
* @creed The only constant is change ! ! !
*/
public static void doDeleteFile(List<File> filesList){
if(filesList.size() > 0){
for (File file : filesList) {
try {
file.delete();
} catch (Exception e) {
e.printStackTrace();
System.out.println("删除文件操作出错");
}
}
}
}
}
实体类:
package com.zzdz.performance.infra;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
/**
* <p>
* HttpResponse<br>
*
* </p>
*
* @author XinLau
* @version 1.0
* @since 2019年08月31日 10:08
*/
public class HttpResponse {
/**
* 返回值
*/
private JSONObject body;
/**
* 头信息
*/
private Header[] headers;
/**
* 状态码 0-失败,1-成功
*/
private int statusCode;
/**
* HTTP状态码
*/
private int httpStatusCode;
/**
* 动作原因
*/
private String reasonPhrase;
public JSONObject getBody() {
return body;
}
public void setBody(JSONObject body) {
this.body = body;
}
public Header[] getHeaders() {
return headers;
}
public void setHeaders(Header[] headers) {
this.headers = headers;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public int getHttpStatusCode() {
return httpStatusCode;
}
public void setHttpStatusCode(int httpStatusCode) {
this.httpStatusCode = httpStatusCode;
}
public String getReasonPhrase() {
return reasonPhrase;
}
public void setReasonPhrase(String reasonPhrase) {
this.reasonPhrase = reasonPhrase;
}
}