package com.hl.dziot.util;
import com.alibaba.fastjson.JSONObject;
import com.hl.dziot.entity.PageResult;
import lombok.SneakyThrows;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Map;
/**
* HttpClient工具类
**/
public class HttpClientUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
/**
* 设备地址
*/
public static CloseableHttpClient httpClient;
private final static String USER_NAME = "admin";
private final static String PASS_WORD = "hik12345";
private final static String PREFIX = "http";
public static void httpClient() {
// 摘要认证
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER_NAME, PASS_WORD));
RequestConfig requestConfig = RequestConfig
.custom()
// (ms)
.setConnectTimeout(50000)
.setSocketTimeout(50000)
.setConnectionRequestTimeout(10)
.build();
httpClient = HttpClients
.custom()
.setDefaultRequestConfig(requestConfig)
.setDefaultCredentialsProvider(credentialsProvider)
.build();
}
@SneakyThrows
public static PageResult<?> doPostFormDataForAddFace(String url, String params, File file, String employeeNo) {
logger.info("参数信息 = {}", params);
logger.info("请求地址 = {}", url);
httpClient();
CloseableHttpResponse response;
try {
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("json",
new StringBody(params, ContentType.create("application/json", Consts.UTF_8)));
builder.addBinaryBody("image", file, ContentType.create("image/jpeg"), employeeNo + ".jpg");
HttpEntity reqEntity = builder.build();
httpPost.setEntity(reqEntity);
// 发起请求 并返回请求的响应
response = httpClient.execute(httpPost, HttpClientContext.create());
String resResult = EntityUtils.toString(response.getEntity(), "utf-8");
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return ResultUtil.success(JSONObject.parseObject(resResult));
} else {
return ResultUtil.error(500, "接口异常", JSONObject.parseObject(resResult));
}
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.error();
} finally {
httpClient.close();
}
}
@SneakyThrows
public static PageResult<?> doPutFormDataForUpdateFace(String url, String params, File file, String employeeNo) {
logger.info("参数信息 = {}", params);
logger.info("请求地址 = {}", url);
httpClient();
CloseableHttpResponse response = null;
try {
HttpPut put = new HttpPut(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
// 人脸信息
builder.addPart("json",
new StringBody(params, ContentType.create("application/json", Consts.UTF_8)));
// 图片信息
builder.addBinaryBody("image", file, ContentType.create("image/jpeg"), employeeNo + ".jpg");
HttpEntity reqEntity = builder.build();
put.setEntity(reqEntity);
// 发起请求 并返回请求的响应
response = httpClient.execute(put, HttpClientContext.create());
String resResult = EntityUtils.toString(response.getEntity(), "utf-8");
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return ResultUtil.success(JSONObject.parseObject(resResult));
} else {
return ResultUtil.error(500, "接口异常", JSONObject.parseObject(resResult));
}
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.error();
} finally {
httpClient.close();
}
}
@SneakyThrows
public static PageResult<?> doPostJson(String url, String params) {
logger.info("参数信息 = {}", params);
logger.info("请求地址 = {}", url);
httpClient();
CloseableHttpResponse response = null;
String resResult = "";
try {
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json;charset=UTF-8");
post.setHeader("Accept", "application/json;charset=UTF-8");
post.setEntity(new StringEntity(params, Consts.UTF_8));
response = httpClient.execute(post);
resResult = EntityUtils.toString(response.getEntity(), "utf-8");
logger.info("result = {}", resResult);
JSONObject jsonObject = JSONObject.parseObject(resResult);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return ResultUtil.success(jsonObject);
} else {
return ResultUtil.error(500, "接口异常!", JSONObject.parse(resResult));
}
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.error(500, "接口异常", JSONObject.parseObject(resResult));
} finally {
httpClient.close();
}
}
@SneakyThrows
public static PageResult<?> doGetJson(String url, String params) {
logger.info("参数信息 = {}", params);
logger.info("请求地址 = {}", url);
httpClient();
CloseableHttpResponse response = null;
String resResult = "";
try {
String urlBuilder = constructionParams(url, params);
HttpGet get = new HttpGet(urlBuilder);
get.setHeader("Content-type", "application/json;charset=UTF-8");
get.setHeader("Accept", "application/json;charset=UTF-8");
response = httpClient.execute(get);
resResult = EntityUtils.toString(response.getEntity(), "utf-8");
logger.info("result = {}", resResult);
JSONObject jsonObject = JSONObject.parseObject(resResult);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return ResultUtil.success(jsonObject);
} else {
return ResultUtil.error(500, "接口异常!", jsonObject);
}
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.error(500, "接口异常", JSONObject.parseObject(resResult));
} finally {
httpClient.close();
}
}
@SneakyThrows
public static PageResult<?> doPutJson(String url, String params) {
logger.info("参数信息 = {}", params);
logger.info("请求地址 = {}", url);
httpClient();
CloseableHttpResponse response;
String resResult;
try {
HttpPut put = new HttpPut(url);
put.setHeader("Content-type", "application/json;charset=UTF-8");
put.setHeader("Accept", "application/json;charset=UTF-8");
put.setEntity(new StringEntity(params, Consts.UTF_8));
response = httpClient.execute(put);
resResult = EntityUtils.toString(response.getEntity(), "utf-8");
logger.info("result = {}", resResult);
JSONObject jsonObject = JSONObject.parseObject(resResult);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return ResultUtil.success(jsonObject);
} else {
return ResultUtil.error(500, "接口异常!", JSONObject.parse(resResult));
}
} catch (Exception e) {
logger.info("方法异常{}", e.getMessage());
return ResultUtil.error();
} finally {
httpClient.close();
}
}
@SneakyThrows
public static PageResult<?> doPutText(String url, String params) {
logger.info("参数信息 = {}", params);
logger.info("请求地址 = {}", url);
httpClient();
CloseableHttpResponse response;
String resResult;
try {
HttpPut put = new HttpPut(url);
put.setEntity(new StringEntity(params, Consts.UTF_8));
response = httpClient.execute(put);
resResult = EntityUtils.toString(response.getEntity(), "utf-8");
logger.info("result = {}", resResult);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return ResultUtil.success(resResult);
} else {
return ResultUtil.error(500, "接口异常!", resResult);
}
} catch (Exception e) {
logger.info("方法异常{}", e.getMessage());
return ResultUtil.error();
} finally {
httpClient.close();
}
}
@SneakyThrows
public static PageResult<String> doDeleteJson(String url, String params) {
logger.info("url == {}", url);
logger.info("params == {}", params);
httpClient();
CloseableHttpResponse response;
String resResult;
try {
String urlBuilder = constructionParams(url, params);
HttpDelete delete = new HttpDelete(urlBuilder);
delete.setHeader("Content-type", "application/json;charset=UTF-8");
delete.setHeader("Accept", "application/json;charset=UTF-8");
response = httpClient.execute(delete);
logger.info("DELETE 返回状态:" + response.getStatusLine());
resResult = EntityUtils.toString(response.getEntity());
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
logger.info("Request successfully executed");
return ResultUtil.success(JSONObject.parseObject(resResult));
} else {
return ResultUtil.error(500, "接口异常", JSONObject.parseObject(resResult));
}
} catch (Exception e) {
return ResultUtil.error();
} finally {
httpClient.close();
}
}
@SneakyThrows
public static PageResult<String> doPostXml(String url, String params, File file, String fileParamName) {
logger.info("url == {}", url);
logger.info("params == {}", params);
httpClient();
CloseableHttpResponse response;
try {
HttpPost post = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (null != file) {
builder.addBinaryBody(
fileParamName,
new FileInputStream(file),
ContentType.APPLICATION_XML,
file.getName());
}
if (Strings.isNotBlank(params)) {
JSONObject paramsObject = JSONObject.parseObject(params);
Iterator<Map.Entry<String, Object>> iterator = paramsObject.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
String key = entry.getKey();
Object value = entry.getValue();
builder.addTextBody(key, String.valueOf(value), ContentType.TEXT_PLAIN);
}
}
HttpEntity multipart = builder.build();
post.setHeader("Accept", "application/xml;charset=UTF-8");
post.setEntity(multipart);
response = httpClient.execute(post);
logger.info("POST 返回状态:" + response.getStatusLine());
String resResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
logger.info("Request successfully executed");
return ResultUtil.success(resResult);
} else {
return ResultUtil.error(500, "接口异常", resResult);
}
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.error();
} finally {
httpClient.close();
}
}
@SneakyThrows
public static PageResult<String> doPutFormData(String url, String params) {
return doPutFormData(url, params, null, "");
}
@SneakyThrows
public static PageResult<String> doPutFormData(String url, String params, File file, String fileParamName) {
logger.info("url == {}", url);
logger.info("params == {}", params);
httpClient();
CloseableHttpResponse response = null;
String resResult = "";
try {
HttpPut put = new HttpPut(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (file != null) {
builder.addBinaryBody(
fileParamName,
new FileInputStream(file),
ContentType.MULTIPART_FORM_DATA,
file.getName());
}
if (Strings.isNotBlank(params)) {
JSONObject paramsObject = JSONObject.parseObject(params);
Iterator<Map.Entry<String, Object>> iterator = paramsObject.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
String key = entry.getKey();
Object value = entry.getValue();
builder.addTextBody(key, String.valueOf(value), ContentType.TEXT_PLAIN);
}
}
HttpEntity multipart = builder.build();
put.setHeader("Accept", "application/json;charset=UTF-8");
put.setEntity(multipart);
response = httpClient.execute(put);
logger.info("PUT 返回状态:" + response.getStatusLine());
resResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
logger.info("Request successfully executed");
return ResultUtil.success(JSONObject.parseObject(resResult));
} else {
return ResultUtil.error(500, "接口异常", JSONObject.parseObject(resResult));
}
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.error();
} finally {
httpClient.close();
}
}
private static String constructionParams(String url, String params) {
StringBuilder urlBuilder = new StringBuilder(url);
if (!"".equals(params)) {
JSONObject paramObject = JSONObject.parseObject(params);
Iterator<Map.Entry<String, Object>> iterator = paramObject.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> next = iterator.next();
String key = next.getKey();
String valueOf = String.valueOf(next.getValue());
String param = "&" + key + "=" + valueOf;
urlBuilder.append(param);
}
}
return urlBuilder.toString();
}
public static String getIsApiUrl(String ip, Integer port) {
return PREFIX + "://" + ip + ":" + port;
}
}