提交 f9d42a75 authored 作者: inroi's avatar inroi

微调

上级 90fc9dc0
/* /*
SQLyog Enterprise v13.1.1 (64 bit) SQLyog Enterprise v13.1.1 (64 bit)
MySQL - 5.7.25 : Database - db_integrate MySQL - 5.7.25 : Database - db_integrate_shop
********************************************************************* *********************************************************************
*/ */
...@@ -12,9 +12,9 @@ MySQL - 5.7.25 : Database - db_integrate ...@@ -12,9 +12,9 @@ MySQL - 5.7.25 : Database - db_integrate
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`db_integrate` /*!40100 DEFAULT CHARACTER SET utf8 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`db_integrate_shop_shop` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `db_integrate`; USE `db_integrate_shop`;
/*Table structure for table `qrtz_blob_triggers` */ /*Table structure for table `qrtz_blob_triggers` */
......
...@@ -7,8 +7,9 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -7,8 +7,9 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import java.io.IOException; import java.util.HashMap;
import java.util.*; import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
...@@ -25,9 +26,9 @@ public class CommonGetApi { ...@@ -25,9 +26,9 @@ public class CommonGetApi {
String result = ""; String result = "";
try { try {
if (StringUtil.isNotBlank(json)) { if (StringUtil.isNotBlank(json)) {
result = HttpClientUtil.sendPost(config.get("requestAddress"), json); result = HttpUtil.httpPost(config.get("requestAddress"), json).getBody();
} else { } else {
result = HttpClientUtil.sendGet(config.get("requestAddress")); result = HttpUtil.httpGet(config.get("requestAddress")).getBody();
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
...@@ -61,10 +62,10 @@ public class CommonGetApi { ...@@ -61,10 +62,10 @@ public class CommonGetApi {
public String commonSendBySync(Map<String, String> config, String json, String queueId) { public String commonSendBySync(Map<String, String> config, String json, String queueId) {
try { try {
String result = HttpClientUtil.sendPost(config.get("responseAddress"), json); String result = HttpUtil.httpPost(config.get("responseAddress"), json).getBody();
thirdPartyLogUtil.thirdPartyLogCreate(config.get("name"), config.get("docType"), queueId, config.get("configureDirection"), json, result); thirdPartyLogUtil.thirdPartyLogCreate(config.get("name"), config.get("docType"), queueId, config.get("configureDirection"), json, result);
return result; return result;
} catch (IOException e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return ""; return "";
} }
......
...@@ -2,12 +2,14 @@ package com.system.api; ...@@ -2,12 +2,14 @@ package com.system.api;
import com.system.constants.Constants; import com.system.constants.Constants;
import com.system.transfer.form.FormFieldMappingDetailOutVoRecords; import com.system.transfer.form.FormFieldMappingDetailOutVoRecords;
import com.system.utils.*; import com.system.utils.FormFieldMappingUtil;
import com.system.utils.HttpUtil;
import com.system.utils.JsonUtil;
import com.system.utils.ThirdPartyLogUtil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -30,7 +32,7 @@ public class CommonPostApi { ...@@ -30,7 +32,7 @@ public class CommonPostApi {
Map<String, Object> data = CommonApi.purchaseData(config, dataList, fieldList); Map<String, Object> data = CommonApi.purchaseData(config, dataList, fieldList);
String result = HttpClientUtil.sendPost(config.get(""), JsonUtil.toString(data)); String result = HttpUtil.httpPost(config.get(""), JsonUtil.toString(data)).getBody();
Map<String, Object> map = JsonUtil.toMap(result, String.class, Object.class); Map<String, Object> map = JsonUtil.toMap(result, String.class, Object.class);
if (!CollectionUtils.isEmpty(map)) { if (!CollectionUtils.isEmpty(map)) {
if (Constants.SUCCESS_CODE.equals(String.valueOf(map.get(Constants.SUCCESS_NAME)))) { if (Constants.SUCCESS_CODE.equals(String.valueOf(map.get(Constants.SUCCESS_NAME)))) {
...@@ -47,7 +49,7 @@ public class CommonPostApi { ...@@ -47,7 +49,7 @@ public class CommonPostApi {
thirdPartyLogUtil.thirdPartyLogCreate(config.get("name"), config.get("docType"), queueId, config.get("configureDirection"), JsonUtil.toString(data), result, flag); thirdPartyLogUtil.thirdPartyLogCreate(config.get("name"), config.get("docType"), queueId, config.get("configureDirection"), JsonUtil.toString(data), result, flag);
return JsonUtil.toString(response); return JsonUtil.toString(response);
} catch (IOException e) { } catch (Exception e) {
response.put("message", e.getMessage()); response.put("message", e.getMessage());
response.put("success", false); response.put("success", false);
return JsonUtil.toString(response); return JsonUtil.toString(response);
......
package com.system.controller; package com.system.controller;
import com.system.transfer.platform.PlatformDockingShoppingMallCommodityInVo;
import com.system.transfer.response.RestResponse;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
...@@ -9,4 +14,19 @@ import org.springframework.web.bind.annotation.RestController; ...@@ -9,4 +14,19 @@ import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@RequestMapping("/api") @RequestMapping("/api")
public class CommonHttpController { public class CommonHttpController {
@ApiOperation("触发平台对接商城会员")
@GetMapping("/platform/docking/shopping/mall/member")
public RestResponse platformDockingShoppingMallMember() {
return RestResponse.success();
}
@ApiOperation("触发平台对接商城会员")
@GetMapping("/platform/docking/shopping/mall/commodity")
public RestResponse platformDockingShoppingMallCommodity(@ModelAttribute PlatformDockingShoppingMallCommodityInVo inVo) {
System.out.println(inVo);
return RestResponse.success();
}
} }
package com.system.scheduler; package com.system.scheduler;
import com.system.serivce.impl.DockingDistributionServiceImpl; import com.system.serivce.impl.DockingDistributionServiceImpl;
import com.system.utils.HttpClientUtil; import com.system.utils.HttpUtil;
import com.system.utils.JsonUtil; import com.system.utils.JsonUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -27,7 +27,7 @@ public class SecretScheduler { ...@@ -27,7 +27,7 @@ public class SecretScheduler {
@Scheduled(fixedRate = 1000 * 60 * 15) @Scheduled(fixedRate = 1000 * 60 * 15)
public void configureTasks() { public void configureTasks() {
String result = HttpClientUtil.sendGet("http://192.168.0.34:8080/api/v1/getSign"); String result = HttpUtil.httpGet("http://192.168.0.34:8080/api/v1/getSign").getBody();
Map<String, Object> map = JsonUtil.toMap(result, String.class, Object.class); Map<String, Object> map = JsonUtil.toMap(result, String.class, Object.class);
dockingDistributionServiceImpl.setSecret(String.valueOf(map.get("data"))); dockingDistributionServiceImpl.setSecret(String.valueOf(map.get("data")));
} }
......
...@@ -3,7 +3,7 @@ package com.system.serivce.impl; ...@@ -3,7 +3,7 @@ package com.system.serivce.impl;
import com.system.constants.Constants; import com.system.constants.Constants;
import com.system.serivce.IDockingDistributionService; import com.system.serivce.IDockingDistributionService;
import com.system.transfer.response.RestResponse; import com.system.transfer.response.RestResponse;
import com.system.utils.HttpClientUtil; import com.system.utils.HttpUtil;
import com.system.utils.JsonUtil; import com.system.utils.JsonUtil;
import com.system.utils.StringUtil; import com.system.utils.StringUtil;
import com.system.utils.ThirdPartyLogUtil; import com.system.utils.ThirdPartyLogUtil;
...@@ -11,7 +11,6 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -11,7 +11,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
...@@ -35,11 +34,11 @@ public class DockingDistributionServiceImpl implements IDockingDistributionServi ...@@ -35,11 +34,11 @@ public class DockingDistributionServiceImpl implements IDockingDistributionServi
public String dockingDistributionMemberCreate(String queueId, Map<String, Object> data) { public String dockingDistributionMemberCreate(String queueId, Map<String, Object> data) {
try { try {
data.put("secret", secret); data.put("secret", secret);
String result = HttpClientUtil.sendPost("http://192.168.0.34:8080/api/v1/memberAdd", JsonUtil.toString(data)); String result = HttpUtil.httpPost("http://192.168.0.34:8080/api/v1/memberAdd", JsonUtil.toString(data)).getBody();
thirdPartyLogUtil.thirdPartyLogCreate("分销会员创建", "0002", queueId, "平台->分销", JsonUtil.toString(data), StringUtil.replaceBlank(result)); thirdPartyLogUtil.thirdPartyLogCreate("分销会员创建", "0002", queueId, "平台->分销", JsonUtil.toString(data), StringUtil.replaceBlank(result));
return result; return result;
} catch (IOException e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return ""; return "";
} }
...@@ -49,11 +48,11 @@ public class DockingDistributionServiceImpl implements IDockingDistributionServi ...@@ -49,11 +48,11 @@ public class DockingDistributionServiceImpl implements IDockingDistributionServi
public String dockingDistributionTransactionCreate(String queueId, Map<String, Object> data) { public String dockingDistributionTransactionCreate(String queueId, Map<String, Object> data) {
try { try {
data.put("secret", secret); data.put("secret", secret);
String result = HttpClientUtil.sendPost("http://192.168.0.34:8080/api/v1/trade", JsonUtil.toString(data)); String result = HttpUtil.httpPost("http://192.168.0.34:8080/api/v1/trade", JsonUtil.toString(data)).getBody();
thirdPartyLogUtil.thirdPartyLogCreate("分销交易创建", "0001", queueId, "平台->分销", JsonUtil.toString(data), StringUtil.replaceBlank(result)); thirdPartyLogUtil.thirdPartyLogCreate("分销交易创建", "0001", queueId, "平台->分销", JsonUtil.toString(data), StringUtil.replaceBlank(result));
return result; return result;
} catch (IOException e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return ""; return "";
} }
...@@ -67,14 +66,14 @@ public class DockingDistributionServiceImpl implements IDockingDistributionServi ...@@ -67,14 +66,14 @@ public class DockingDistributionServiceImpl implements IDockingDistributionServi
data.put("userId", "admin"); data.put("userId", "admin");
data.put("amount", "1"); data.put("amount", "1");
data.put("accountType", "2"); data.put("accountType", "2");
String result = HttpClientUtil.sendPost("http://192.168.0.34:8080/api/v1/withdraw", JsonUtil.toString(data)); String result = HttpUtil.httpPost("http://192.168.0.34:8080/api/v1/withdraw", JsonUtil.toString(data)).getBody();
Map<String, Object> map = JsonUtil.toMap(result, String.class, Object.class); Map<String, Object> map = JsonUtil.toMap(result, String.class, Object.class);
if (CollectionUtils.isEmpty(map) || !Constants.SUCCESS_CODE.equals(String.valueOf(map.get(Constants.SUCCESS_NAME)))) { if (CollectionUtils.isEmpty(map) || !Constants.SUCCESS_CODE.equals(String.valueOf(map.get(Constants.SUCCESS_NAME)))) {
return RestResponse.fail("新增提现失败"); return RestResponse.fail("新增提现失败");
} }
return RestResponse.success(); return RestResponse.success();
} catch (IOException e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return RestResponse.fail("新增提现失败"); return RestResponse.fail("新增提现失败");
} }
...@@ -86,11 +85,11 @@ public class DockingDistributionServiceImpl implements IDockingDistributionServi ...@@ -86,11 +85,11 @@ public class DockingDistributionServiceImpl implements IDockingDistributionServi
Map<String, Object> data = new HashMap<>(2); Map<String, Object> data = new HashMap<>(2);
data.put("secret", secret); data.put("secret", secret);
data.put("memberId", memberId); data.put("memberId", memberId);
String result = HttpClientUtil.sendPost("http://192.168.0.34:8080/api/v1/subordinate", JsonUtil.toString(data)); String result = HttpUtil.httpPost("http://192.168.0.34:8080/api/v1/subordinate", JsonUtil.toString(data)).getBody();
thirdPartyLogUtil.thirdPartyLogCreate("分销会员下级查询", "0001", queueId, "平台->分销", JsonUtil.toString(data), StringUtil.replaceBlank(result)); thirdPartyLogUtil.thirdPartyLogCreate("分销会员下级查询", "0001", queueId, "平台->分销", JsonUtil.toString(data), StringUtil.replaceBlank(result));
return result; return result;
} catch (IOException e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return ""; return "";
} }
...@@ -102,11 +101,11 @@ public class DockingDistributionServiceImpl implements IDockingDistributionServi ...@@ -102,11 +101,11 @@ public class DockingDistributionServiceImpl implements IDockingDistributionServi
Map<String, Object> data = new HashMap<>(2); Map<String, Object> data = new HashMap<>(2);
data.put("secret", secret); data.put("secret", secret);
data.put("memberId", memberId); data.put("memberId", memberId);
String result = HttpClientUtil.sendPost("http://192.168.0.34:8080/api/v1/member/balance", JsonUtil.toString(data)); String result = HttpUtil.httpPost("http://192.168.0.34:8080/api/v1/member/balance", JsonUtil.toString(data)).getBody();
thirdPartyLogUtil.thirdPartyLogCreate("分销会员余额查询", "0001", queueId, "平台->分销", JsonUtil.toString(data), StringUtil.replaceBlank(result)); thirdPartyLogUtil.thirdPartyLogCreate("分销会员余额查询", "0001", queueId, "平台->分销", JsonUtil.toString(data), StringUtil.replaceBlank(result));
return result; return result;
} catch (IOException e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return ""; return "";
} }
...@@ -119,12 +118,12 @@ public class DockingDistributionServiceImpl implements IDockingDistributionServi ...@@ -119,12 +118,12 @@ public class DockingDistributionServiceImpl implements IDockingDistributionServi
data.put("secret", secret); data.put("secret", secret);
data.put("memberId", memberId); data.put("memberId", memberId);
data.put("offset", 0); data.put("offset", 0);
data.put("limit", 14); data.put("limit", 10000);
String result = HttpClientUtil.sendPost("http://192.168.0.34:8080/api/v1/member/profit", JsonUtil.toString(data)); String result = HttpUtil.httpPost("http://192.168.0.34:8080/api/v1/member/profit", JsonUtil.toString(data)).getBody();
thirdPartyLogUtil.thirdPartyLogCreate("分销会员收益查询", "0001", queueId, "平台->分销", JsonUtil.toString(data), StringUtil.replaceBlank(result)); thirdPartyLogUtil.thirdPartyLogCreate("分销会员收益查询", "0001", queueId, "平台->分销", JsonUtil.toString(data), StringUtil.replaceBlank(result));
return result; return result;
} catch (IOException e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return ""; return "";
} }
......
package com.system.serivce.impl; package com.system.serivce.impl;
import com.system.serivce.IDockingShoppingMallService; import com.system.serivce.IDockingShoppingMallService;
import com.system.utils.HttpClientUtil; import com.system.utils.HttpUtil;
import com.system.utils.JsonUtil; import com.system.utils.JsonUtil;
import com.system.utils.ThirdPartyLogUtil; import com.system.utils.ThirdPartyLogUtil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -26,14 +26,8 @@ public class DockingShoppingMallServiceImpl implements IDockingShoppingMallServi ...@@ -26,14 +26,8 @@ public class DockingShoppingMallServiceImpl implements IDockingShoppingMallServi
data.put("startTime", "2019-01-01+00:00:00"); data.put("startTime", "2019-01-01+00:00:00");
data.put("endTime", "2022-10-12+23:59:59"); data.put("endTime", "2022-10-12+23:59:59");
StringBuilder param = new StringBuilder(); String result = HttpUtil.httpGet("http://192.168.2.212:81/apis/order/order/page?current=1&size=100", data).getBody();
for (Map.Entry<String, Object> entry : data.entrySet()) {
param.append("&").append(entry.getKey()).append("=").append(entry.getValue());
}
String result = HttpClientUtil.sendGet("http://192.168.2.212:81/apis/order/order/page?current=1&size=100" + param.toString());
System.out.println(result); System.out.println(result);
return result; return result;
} }
...@@ -43,12 +37,7 @@ public class DockingShoppingMallServiceImpl implements IDockingShoppingMallServi ...@@ -43,12 +37,7 @@ public class DockingShoppingMallServiceImpl implements IDockingShoppingMallServi
data.put("startTime", "2019-01-01+00:00:00"); data.put("startTime", "2019-01-01+00:00:00");
data.put("endTime", "2022-10-12+23:59:59"); data.put("endTime", "2022-10-12+23:59:59");
StringBuilder param = new StringBuilder(); String result = HttpUtil.httpGet("http://192.168.2.212:81/apis/prod/prod/page?current=1&size=100", data).getBody();
for (Map.Entry<String, Object> entry : data.entrySet()) {
param.append("&").append(entry.getKey()).append("=").append(entry.getValue());
}
String result = HttpClientUtil.sendGet("http://192.168.2.212:81/apis/prod/prod/page?current=1&size=100" + param.toString());
System.out.println(result); System.out.println(result);
} }
...@@ -66,7 +55,7 @@ public class DockingShoppingMallServiceImpl implements IDockingShoppingMallServi ...@@ -66,7 +55,7 @@ public class DockingShoppingMallServiceImpl implements IDockingShoppingMallServi
param.append(entry.getKey()).append("=").append(entry.getValue()); param.append(entry.getKey()).append("=").append(entry.getValue());
} }
} }
String result = HttpClientUtil.sendGet("https://console-mock.apipost.cn/app/mock/project/a0605054-5c08-47a3-e61e-76782a1bc5aa/member/list?" + param.toString()); String result = HttpUtil.httpGet("https://console-mock.apipost.cn/app/mock/project/a0605054-5c08-47a3-e61e-76782a1bc5aa/member/list").getBody();
thirdPartyLogUtil.thirdPartyLogCreate("商城会员查询", "0000", queueId, "商城->平台", JsonUtil.toString(data), result); thirdPartyLogUtil.thirdPartyLogCreate("商城会员查询", "0000", queueId, "商城->平台", JsonUtil.toString(data), result);
return result; return result;
......
package com.system.transfer.platform;
import lombok.Data;
/**
* @author Inori
*/
@Data
public class PlatformDockingShoppingMallCommodityInVo {
/**
* ID
*/
private Integer id;
}
package com.system.utils;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* 发送请求工具类
*
* @author Lnori
*/
public class HttpClientUtil {
private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
public static final String[] ENCODES = new String[]{"UTF-8", "GBK", "GB2312", "ISO-8859-1", "ISO-8859-2"};
/**
* 发送Get请求
*/
public static String sendGet(String url) {
log.info("【Get请求】Url: {}", url);
/*
* 1.生成HttpClient对象并设置参数
*/
HttpClient httpClient = new HttpClient();
//设置Http连接超时为10秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
/*
* 2.生成GetMethod对象并设置参数
*/
GetMethod getMethod = new GetMethod(url);
//设置get请求超时为10秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);
//设置请求重试处理,用的是默认的重试处理:请求三次
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response;
/*
* 3.执行HTTP GET 请求
*/
try {
int statusCode = httpClient.executeMethod(getMethod);
/*
* 4.判断访问的状态码
*/
if (statusCode != HttpStatus.SC_OK) {
log.error("请求出错:{}", getMethod.getStatusLine());
}
/*
* 5.处理HTTP响应内容
*/
//读取为字节数组
byte[] responseBody = getMethod.getResponseBody();
response = new String(responseBody, "GBK");
log.info("【Get请求】返回值: {}", response);
return response;
} catch (HttpException e) {
log.error("请检查输入的URL!");
} catch (IOException e) {
log.error("发生网络异常!");
} finally {
/*
* 6.释放连接
*/
getMethod.releaseConnection();
httpClient.getHttpConnectionManager().closeIdleConnections(0L);
}
return "";
}
public static String sendPost(String url, String json) throws IOException {
log.info("【Post请求】Url: {}", url);
/*
* 1.生成HttpClient对象并设置参数
*/
HttpClient httpClient = new HttpClient();
//设置Http连接超时为10秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
/*
* 2.生成PostMethod对象并设置参数
*/
PostMethod postMethod = new PostMethod(url);
//设置post请求超时为10秒
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);
//设置请求重试处理,用的是默认的重试处理:请求三次
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
//设置请求头
postMethod.addRequestHeader("Content-Type", "application/json");
/*
* 3.执行HTTP GET 请求
*/
String response = "";
try {
//json格式的参数解析
RequestEntity entity = new StringRequestEntity(json, "application/json", "UTF-8");
postMethod.setRequestEntity(entity);
int statusCode = httpClient.executeMethod(postMethod);
/*
* 4.判断访问的状态码
*/
if (statusCode != HttpStatus.SC_OK) {
log.error("请求出错:{}", postMethod.getStatusLine());
}
/*
* 5.处理HTTP响应内容
*/
byte[] responseBody = postMethod.getResponseBody();
response = new String(responseBody, StandardCharsets.UTF_8);
log.info("【Post请求】返回值: {}", response);
return response;
} finally {
/*
* 6.释放连接
*/
postMethod.releaseConnection();
httpClient.getHttpConnectionManager().closeIdleConnections(0L);
}
}
}
package com.system.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
import java.util.Set;
/**
* @author Inori
*/
public class HttpUtil {
private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
/**
* 连接超时时间
*/
private static final int CONN_TIMEOUT = 10000;
/**
* 请求超时时间
*/
private static final int READ_TIMEOUT = 10000;
/**
* 请求工具
*/
private static RestTemplate restTemplate;
static {
//设置超时时间
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(CONN_TIMEOUT);
requestFactory.setReadTimeout(READ_TIMEOUT);
restTemplate = new RestTemplate(requestFactory);
}
/**
* 设置header公共参数
*/
private static HttpHeaders initHeader() {
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", "application/json");
headers.add("Accpet-Encoding", "gzip");
headers.add("Content-Encoding", "UTF-8");
headers.add("Content-Type", "application/json; charset=UTF-8");
return headers;
}
/**
* 设置header参数
*/
private static void setHeaderParam(HttpHeaders httpHeaders, Map<String, Object> headers) {
if (!CollectionUtils.isEmpty(headers)) {
Set<String> keys = headers.keySet();
for (String key : keys) {
httpHeaders.add(key, headers.get(key).toString());
}
}
}
/**
* 发送Get请求
*/
public static ResponseEntity<String> httpGet(String url) {
//初始化header公共参数
HttpHeaders httpHeaders = initHeader();
//发送请求
HttpEntity<String> httpEntity = new HttpEntity<>(null, httpHeaders);
return restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
}
/**
* 发送Get请求
*/
public static ResponseEntity<String> httpGet(String url, Map<String, Object> param) {
//初始化header公共参数
HttpHeaders httpHeaders = initHeader();
//组装查询参数
url = setParam(url, param);
//发送请求
HttpEntity<String> httpEntity = new HttpEntity<>(null, httpHeaders);
log.info("【Get请求】Url: {}", url);
return restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
}
private static String setParam(String url, Map<String, Object> param) {
Set<String> keys = param.keySet();
StringBuilder builder = new StringBuilder();
builder.append("?");
for (String key : keys) {
builder.append(key).append("=").append(param.get(key)).append("&");
}
builder.deleteCharAt(builder.lastIndexOf("&"));
url = url + builder.toString();
return url;
}
/**
* 发送Get请求
*/
public static ResponseEntity<String> httpGet(String url, Map<String, Object> headers, Map<String, Object> param) {
//如果查询参数为空,则调用不带参数的Get请求
if (CollectionUtils.isEmpty(param)) {
return httpGet(url, headers);
}
//组装查询参数
url = setParam(url, param);
//发送请求
log.info("【Get请求】Url: {}", url);
return httpGet(url, headers);
}
/**
* 发送Post请求
*/
public static ResponseEntity<String> httpPost(String url, String json) {
//初始化header公共参数
HttpHeaders httpHeaders = initHeader();
//发送请求
log.info("【Post请求】Url: {}", url);
return toPost(url, httpHeaders, json);
}
/**
* 发送Post请求
*/
public static ResponseEntity<String> httpPost(String url, Map<String, Object> header, String json) {
//初始化header公共参数
HttpHeaders httpHeaders = initHeader();
setHeaderParam(httpHeaders, header);
//发送请求
log.info("【Post请求】Url: {}", url);
return toPost(url, httpHeaders, json);
}
/**
* 发送请求
*/
private static ResponseEntity<String> toPost(String url, HttpHeaders httpHeaders, String json) {
HttpEntity<String> httpEntity = new HttpEntity<>(json, httpHeaders);
return restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
}
}
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论