package ;
import ;
import ;
import ;
import .log4j.Log4j;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .*;
import ;
import ;
import static ;
import static ..;
@Log4j
@Component
public class HttpClientUtils {
// 默认字符集
private static final String ENCODING = "UTF-8";
/**
* @param url 请求地址
* @param headers 请求头
* @param data 请求实体
* @param encoding 字符集
* @return String
* @throws
* @Title: sendPost
* @Description: TODO(发送post请求)
*/
public static String sendPost(String url, Map<String, String> headers, JSONObject data, String encoding) {
("进入post请求方法...");
("请求入参:URL= " + url);
("请求入参:headers=" + (headers));
("请求入参:data=" + (data));
// 请求返回结果
String resultJson = null;
// 创建Client
CloseableHttpClient client = ();
// 创建HttpPost对象
HttpPost httpPost = new HttpPost();
// RequestConfig requestConfig = ()
//
// .setConnectTimeout(50000).setConnectionRequestTimeout(10000)
//
// .setSocketTimeout(50000).build();
//
// (requestConfig);
try {
// 设置请求地址
(new URI(url));
// 设置请求头
if (headers != null) {
Header[] allHeader = new BasicHeader[()];
int i = 0;
for (<String, String> entry : ()) {
allHeader[i] = new BasicHeader((), ());
i++;
}
(allHeader);
}
// 创建请求参数
List<NameValuePair> list = new LinkedList<>();
BasicNameValuePair param = new BasicNameValuePair("param", ("param"));
(param);
// 使用URL实体转换工具
UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
(entityParam);
// 发送请求,返回响应对象
long http = ();
("POS--HTTP请求开始" + http);
CloseableHttpResponse response = (httpPost);
double durationHttp = (int) ((() - http) / 1000.0);
("POS--HTTP请求结束" + () + "HTTP请求耗时耗时:" + durationHttp);
// 获取响应状态
int status = ().getStatusCode();
if (status == HttpStatus.SC_OK) {
// 获取响应结果
resultJson = ((), encoding);
} else {
("响应失败,状态码:" + status);
}
} catch (Exception e) {
("发送post请求失败", e);
} finally {
();
}
return resultJson;
}
/**
* @param url 请求地址
* @param data 请求实体
* @return String
* @throws
* @Title: sendPost
* @Description: TODO(发送post请求 , 请求数据默认使用json格式 , 默认使用UTF - 8编码)
* @author wangxy
* @date 2018年5月10日 下午4:37:28
*/
public static String sendPost(String url, JSONObject data) {
// 设置默认请求头
Map<String, String> headers = new HashMap<>();
("content-type", "application/x-www-form-urlencoded");
return sendPost(url, headers, data, ENCODING);
}
/**
* @param url 请求地址
* @param params 请求实体
* @return String
* @throws
* @Title: sendPost
* @Description: TODO(发送post请求 , 请求数据默认使用json格式 , 默认使用UTF - 8编码)
* @author wangxy
* @date 2018年5月10日 下午6:11:05
*/
public static String sendPost(String url, Map<String, Object> params) {
// 设置默认请求头
Map<String, String> headers = new HashMap<>();
("content-type", "application/json");
// 将map转成json
JSONObject data = ((params));
return sendPost(url, headers, data, ENCODING);
}
/**
* @param url 请求地址
* @param headers 请求头
* @param data 请求实体
* @return String
* @throws
* @Title: sendPost
* @Description: TODO(发送post请求 , 请求数据默认使用UTF - 8编码)
* @author wangxy
* @date 2018年5月10日 下午4:39:03
*/
public static String sendPost(String url, Map<String, String> headers, JSONObject data) {
return sendPost(url, headers, data, ENCODING);
}
/**
* @param url 请求地址
* @param headers 请求头
* @param params 请求实体
* @return String
* @throws
* @Title: sendPost
* @Description:(发送post请求,请求数据默认使用UTF-8编码)
* @author wangxy
* @date 2018年5月10日 下午5:58:40
*/
public static String sendPost(String url, Map<String, String> headers, Map<String, String> params) {
// 将map转成json
JSONObject data = ((params));
return sendPost(url, headers, data, ENCODING);
}
/**
* @param url 请求地址
* @param params 请求参数
* @param encoding 编码
* @return String
* @throws
* @Title: sendGet
* @Description: TODO(发送get请求)
* @author wangxy
* @date 2018年5月14日 下午2:39:01
*/
public static String sendGet(String url, Map<String, Object> params, String encoding) {
("进入get请求方法...");
("请求入参:URL= " + url);
("请求入参:params=" + (params));
// 请求结果
String resultJson = null;
// 创建client
CloseableHttpClient client = ();
// 创建HttpGet
HttpGet httpGet = new HttpGet();
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
// 封装参数
if (params != null) {
for (String key : ()) {
(key, (key).toString());
}
}
URI uri = ();
("请求地址:" + uri);
// 设置请求地址
(uri);
// 发送请求,返回响应对象
CloseableHttpResponse response = (httpGet);
// 获取响应状态
int status = ().getStatusCode();
if (status == HttpStatus.SC_OK) {
// 获取响应数据
resultJson = ((), encoding);
} else {
("响应失败,状态码:" + status);
}
} catch (Exception e) {
("发送get请求失败", e);
} finally {
();
}
return resultJson;
}
/**
* 获取 DB文件
*
* @param url 请求地址
* @return boolean
* @throws
* @Title: sendGet
* @Description: TODO(发送get请求)
* @author wangxy
* @date 2018年5月14日 下午2:39:01
*/
public static String sendGet(String url, String flieName) {
("进入get请求方法...");
("请求入参:URL= " + url);
("请求入参:FlieName= " + flieName);
// 请求结果
// String resultJson = null;
InputStream in = null;
FileOutputStream fout = null;
// 创建client
CloseableHttpClient client = ();
CloseableHttpResponse response = null;
// 创建HttpGet
HttpGet httpGet = new HttpGet();
String pathName = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
URI uri = ();
("请求地址:" + uri);
// 设置请求地址
(uri);
// 发送请求,返回响应对象
response = (httpGet);
// 获取响应状态
int status = ().getStatusCode();
if (status == HttpStatus.SC_OK) {
// 获取响应数据
// resultJson = ((), encoding);
in = ().getContent();
pathName = ("/home/admin/").getPath();
File file = new File(pathName + flieName + ".zip");
fout = new FileOutputStream(file);
int l = -1;
byte[] tmp = new byte[1024];
while ((l = (tmp)) != -1) {
(tmp, 0, l);
// 注意这里如果用(buff)的话,图片会失真,大家可以试试
}
();
();
unZip(file, pathName);
} else {
("响应失败,状态码:" + status);
throw new NDSException("响应失败,状态码:" + status);
}
} catch (Exception e) {
("发送get请求失败", e);
throw new NDSException(e);
} finally {
try {
if (in != null) {
();
}
} catch (Exception e) {
("DB文件下载失败", e);
throw new NDSException(e);
}
try {
();
if (client != null) {
();
}
if (response != null) {
();
}
} catch (Exception e) {
("HTTP 释放失败", e);
throw new NDSException(e);
}
}
return pathName + ".db";
}
/**
* zip解压
*
* @param srcFile zip源文件
* @param destDirPath 解压后的目标文件夹
* @throws RuntimeException 解压失败会抛出运行时异常
*/
public static void unZip(File srcFile, String destDirPath) throws RuntimeException {
long start = ();
// 判断源文件是否存在
if (!()) {
throw new RuntimeException(() + "所指文件不存在");
}
// 开始解压
ZipFile zipFile = null;
try {
zipFile = new ZipFile(srcFile);
Enumeration<?> entries = ();
while (()) {
ZipEntry entry = (ZipEntry) ();
("解压" + ());
// 如果是文件夹,就创建个文件夹
if (()) {
String dirPath = destDirPath + "/" + ();
File dir = new File(dirPath);
();
} else {
// 如果是文件,就先创建一个文件,然后用io流把内容copy过去
File targetFile = new File(destDirPath + "/" + ());
// 保证这个文件的父文件夹必须要存在
if (!().exists()) {
().mkdirs();
}
();
// 将压缩文件内容写入到这个文件中
InputStream is = (entry);
FileOutputStream fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[1024];
while ((len = (buf)) != -1) {
(buf, 0, len);
}
// 关流顺序,先打开的后关闭
();
();
}
}
long end = ();
("解压完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("unzip error from ZipUtils", e);
} finally {
if (zipFile != null) {
try {
();
} catch (IOException e) {
();
}
}
}
}
/**
* @param url 请求地址
* @param params 请求参数
* @return String
* @throws
* @Title: sendGet
* @Description: TODO(发送get请求)
* @author wangxy
* @date 2018年5月14日 下午2:32:39
*/
public static String sendGet(String url, Map<String, Object> params) {
return sendGet(url, params, ENCODING);
}
/**
* @param url 请求地址
* @return String
* @throws
* @Title: sendGet
* @Description: TODO(发送get请求)
* @author wangxy
* @date 2018年5月14日 下午2:33:45
*/
public static String sendGet(String url) {
return sendGet(url, null, ENCODING);
}
public static void main(String[] args) {
sendGet("http://47.97.100.226:333/servlets/binserv/ExportDataDownload?downloadFileName=BOS20_1_20190411193156884.zip", "");
}
/**
* 获取IP地址
*
* @param request
* @return
*/
public static String getIpAddres(HttpServletRequest request) {
String ipAddress = ("x-forwarded-for");
if (ipAddress == null || () == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = ("Proxy-Client-IP");
}
if (ipAddress == null || () == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = ("WL-Proxy-Client-IP");
}
if (ipAddress == null || () == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = ();
if (("127.0.0.1") || ("0:0:0:0:0:0:0:1")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = ();
} catch (UnknownHostException e) {
();
}
ipAddress = ();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ipAddress != null && () > 15) { // "***.***.***.***".length()
// = 15
if ((",") > 0) {
ipAddress = (0, (","));
}
}
return ipAddress;
}
}