一、场景说明
二、实现代码
1. 常量枚举类
/**
* 对接常量类
*/
public interface TripartiteConstant {
/** 请求类型GET */
String REQUEST_TYPE_GET = "GET";
/** 请求类型POST */
String REQUEST_TYPE_POST = "POST";
/** 请求参数 */
String PARAMETER_PARAM = "param";
/** 请求头参数 */
String PARAMETER_TYPE_HEADER = "header";
/** 请求体参数 */
String PARAMETER_TYPE_BODY = "body";
}
2. 请求发送工具类
/**
* 视频监控工具类
*/
@Slf4j
public class RequestSendUtil {
/**
* 发送Post请求,并返回请求结果数据
*
* @param url 请求地址
* @param requestType 请求类型
* @param param 请求参数
* @param contentType 内容类型
* @return 结果
*/
public static JSONObject executeRequest(String url, String requestType, Map<String, Map<String, String>> param, String contentType, Boolean utf8) {
log.info("请求地址:{}", url);
log.info("请求参数:{}", JSONObject.toJSONString(param));
log.info("请求内容类型:{}", contentType);
if (TripartiteConstant.REQUEST_TYPE_POST.equals(requestType)) {
log.info("请求类型:POST...");
return executePostRequest(url, param, contentType, utf8);
} else if (TripartiteConstant.REQUEST_TYPE_GET.equals(requestType)) {
log.info("请求类型:GET...");
return executeGetRequest(url, param, contentType, utf8);
} else {
return null;
}
}
/**
* 发送Post请求,并返回请求结果数据
*
* @param url 请求地址
* @param param 请求参数
* @param contentType 内容类型
* @return 结果
*/
private static JSONObject executePostRequest(String url, Map<String, Map<String, String>> param, String contentType, Boolean utf8) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建HttpPost请求
HttpPost httpPost = new HttpPost(url);
if (!StringUtils.isEmpty(contentType)) {
if (utf8) {
httpPost.addHeader("Content-Type", contentType + ";charset=utf-8");
} else {
httpPost.addHeader("Content-Type", contentType);
}
}
Map<String, String> headerParam = param.getOrDefault(TripartiteConstant.PARAMETER_TYPE_HEADER, null);
headerParameter(httpPost, headerParam);
Map<String, String> bodyParam = param.getOrDefault(TripartiteConstant.PARAMETER_TYPE_BODY, null);
if (contentType.contains("application/json")) {
JSONObject paramData = new JSONObject();
paramData.putAll(bodyParam);
httpPost.setEntity(new StringEntity(JSONObject.toJSONString(paramData)));
} else {
List<NameValuePair> parameters = bodyParameter(bodyParam);
if (!parameters.isEmpty()) {
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);
httpPost.setEntity(entity);
}
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = disposeResponse(response);
} catch (Exception e) {
log.error("三方接口调用失败", e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error("关闭响应失败", e);
}
}
}
return JSONObject.parseObject(resultString);
}
/**
* 发送Get请求
*
* @param url 请求地址
* @param param 请求参数
* @param contentType 内容类型
* @return 结果
*/
private static JSONObject executeGetRequest(String url, Map<String, Map<String, String>> param, String contentType, Boolean utf8) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
URIBuilder uri = new URIBuilder(url);
// 设置请求体参数
Map<String, String> bodyParam = param.getOrDefault(TripartiteConstant.PARAMETER_TYPE_BODY, null);
uri.setParameters(bodyParameter(bodyParam));
// 创建HttpGet请求
HttpGet httpGet = new HttpGet(uri.build());
// 设置请求状态参数
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(3000)
.setSocketTimeout(3000)
.setConnectTimeout(3000).build();
httpGet.setConfig(requestConfig);
if (!StringUtils.isEmpty(contentType)) {
if (utf8) {
httpGet.addHeader("Content-Type", contentType + ";charset=utf-8");
} else {
httpGet.addHeader("Content-Type", contentType);
}
}
// 设置请求头
Map<String, String> headerParam = param.getOrDefault(TripartiteConstant.PARAMETER_TYPE_HEADER, null);
headerParameter(httpGet, headerParam);
// 执行http请求
response = httpClient.execute(httpGet);
resultString = disposeResponse(response);
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
return JSONObject.parseObject(resultString);
}
/**
* 处理响应数据
*
* @param response 响应
* @return 结果
* @throws IOException 异常
*/
private static String disposeResponse(CloseableHttpResponse response) throws IOException {
String res = null;
// 获取返回状态值
int status = response.getStatusLine().getStatusCode();
// 请求成功
if (status == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
res = EntityUtils.toString(httpEntity, "utf-8");
// 关闭资源
EntityUtils.consume(httpEntity);
}
}
return res;
}
/**
* 处理Header参数
*
* @param request 请求对象
* @param param 请求参数
*/
private static void headerParameter(HttpRequestBase request, Map<String, String> param) {
if (param != null) {
for (String item : param.keySet()) {
request.addHeader(item, param.get(item));
}
}
}
/**
* 获取转化后的Body请求参数
*
* @param param 请求参数
* @return 参数对象
*/
private static List<NameValuePair> bodyParameter(Map<String, String> param) {
List<NameValuePair> parameters = new ArrayList<>();
if (param != null) {
for (String key : param.keySet()) {
BasicNameValuePair newParam = new BasicNameValuePair(key, param.get(key));
parameters.add(newParam);
}
}
return parameters;
}
}
3. 服务类
/**
* 三方请求服务
*/
public interface TripartiteRequestService {
/**
* 发送请求
*
* @param param 请求参数
* @return 请求结果
*/
Object sendRequest(Map<String, Map<String, String>> param);
}
4. 服务实现类
/**
* 三方请求服务 实现类
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS)
public class TripartiteRequestServiceImpl implements TripartiteRequestService {
@Override
public Object sendRequest(Map<String, Map<String, String>> param) {
// 解析参数
Map<String, String> urlParam = param.get(TripartiteConstant.PARAMETER_PARAM);
String requestType = urlParam.getOrDefault("requestType", TripartiteConstant.REQUEST_TYPE_POST);
String contentType = urlParam.getOrDefault("contentType", null);
String url = urlParam.getOrDefault("url", null);
String utf8Data = urlParam.getOrDefault("utf8", "false");
Boolean utf8 = Boolean.parseBoolean(utf8Data);
if (url == null) {
throw new RuntimeException("请求地址不能为空");
}
param.remove(TripartiteConstant.PARAMETER_PARAM);
return RequestSendUtil.executeRequest(url, requestType, param, contentType, utf8);
}
}
5. 控制层类
/**
* 开发接口定义控制器
*/
@Slf4j
@RestController
@RequestMapping("/tripartite")
public class RequestTestController {
@Autowired
private TripartiteRequestService tripartiteRequestService;
@PostMapping("/send-request")
public Object sendRequest(@RequestBody Map<String, Map<String, String>> param) {
return tripartiteRequestService.sendRequest(param);
}
}
6. 请求参数
{
"param": {
"url": "http://.......",
"requestType": "POST",
"contentType": "application/json",
"utf8": "false"
},
"header": {
"请求头参数A": ".......",
"请求头参数B": "......."
},
"body": {
"请求头参数A": ".......",
"请求头参数B": ".......",
"请求头参数C": "......."
}
}