2024-12-06 10:13:43 +08:00

169 lines
6.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.ycwl.basic.service;
import com.ycwl.basic.utils.HttpServiceUtil;
import com.ycwl.basic.utils.SslUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Http请求服务
*
* @author songmingsong
*/
@Service
@Slf4j
public class HttpService {
/**
* @param requestUrl
* 请求地址
* @param params
* 参数
* @param encoding
* 编码
* @return String
* @throws Exception
* 抛出的异常新
*/
public String doHttpsPost(String requestUrl, Map<String, String> params, String encoding) throws Exception {
String result = HttpServiceUtil.REQUEST_NO_RESULT;
// build client 对象
CloseableHttpClient httpClient = null;
try {
httpClient = SslUtil.sslHttpClientBuild();
requestUrl = requestUrl.replaceAll("\\s*", "");
HttpPost post = new HttpPost(requestUrl);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
.setConnectionRequestTimeout(1000).setSocketTimeout(5000).build();
post.setConfig(requestConfig);
// 请求首部--可选的User-Agent对于一些服务器必选不加可能不会返回正确结果
post.setHeader("User-Agent",
"Mozilla/5.0 (Linux; U; Android 5.0.2; zh-cn; PLK-UL00 Build/HONORPLK-UL00) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/5.4 TBS/025483 Mobile Safari/533.1 MicroMessenger/6.3.8.56_re6b2553.680 NetType/");
List<NameValuePair> parasList = new ArrayList<NameValuePair>();
if (null != params && params.size() > 0) {
for (String key : params.keySet()) {
NameValuePair param = new BasicNameValuePair(key, params.get(key));
parasList.add(param);
}
}
// Exec Request
HttpEntity paramsEntity = new UrlEncodedFormEntity(parasList, encoding);
post.setEntity(paramsEntity);
CloseableHttpResponse resp = httpClient.execute(post);
// 获得起始行
StatusLine status = resp.getStatusLine();
// 获取实体
if (HttpServiceUtil.success(status)) {
// 获取实体
HttpEntity entity = resp.getEntity();
// 编码格式
result = EntityUtils.toString(entity, encoding);
// 释放实体 response.close();//关闭响应
EntityUtils.consume(entity);
}
} catch (Exception e) {
log.error("doHttpsPost", e);
throw e;
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return result;
}
public String doGet(String requestUrl, String encoding) throws Exception {
String result = HttpServiceUtil.REQUEST_NO_RESULT;
// build client 对象
CloseableHttpClient httpClient = null;
try {
httpClient = SslUtil.sslHttpClientBuild();
requestUrl = requestUrl.replaceAll("\\s*", "");
HttpGet get = new HttpGet(requestUrl);
// 请求首部--可选的User-Agent对于一些服务器必选不加可能不会返回正确结果
get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64;rv:39.0) Gecko/20100101 Firefox/39.0");
get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64;rv:39.0) Gecko/20100101 Firefox/39.0");
// Exec Request
CloseableHttpResponse resp = httpClient.execute(get);
// 获得起始行
StatusLine status = resp.getStatusLine();
if (HttpServiceUtil.success(status)) {
// 获取实体
HttpEntity entity = resp.getEntity();
// 编码格式
result = EntityUtils.toString(entity, encoding);
// 释放实体 response.close();//关闭响应
EntityUtils.consume(entity);
}
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return result;
}
public String doPost(String requestUrl, String jsonData, Map<String, String> headers, String encoding) throws Exception {
String result = HttpServiceUtil.REQUEST_NO_RESULT; // 默认返回值
CloseableHttpClient httpClient = null;
try {
// 使用自定义 SSL 工具类创建支持 HTTPS 的 HttpClient
httpClient = SslUtil.sslHttpClientBuild();
// 清理 URL 中的空格字符
requestUrl = requestUrl.replaceAll("\\s*", "");
HttpPost post = new HttpPost(requestUrl);
// 设置请求头
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> header : headers.entrySet()) {
post.setHeader(header.getKey(), header.getValue());
}
}
// 设置请求体
if (jsonData != null) {
StringEntity entity = new StringEntity(jsonData, encoding);
entity.setContentType("application/json");
post.setEntity(entity);
}
// 执行请求
CloseableHttpResponse response = httpClient.execute(post);
// 获取响应状态码及响应数据
StatusLine status = response.getStatusLine();
if (HttpServiceUtil.success(status)) {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, encoding);
EntityUtils.consume(entity); // 确保释放资源
}
response.close(); // 关闭响应对象
} finally {
if (httpClient != null) {
httpClient.close(); // 关闭 HttpClient
}
}
return result;
}
}