需求
我们现在开发的APP 需要定时将APP收集的预约单发送到另一个DMS系统(服务站), 但是请求DMS系统的接口还需要先登录获取到cookie, 这个cookie是登录DMS系统后返回的Headers中的Set-Cookie的值
已知
DMS登录接口: https://dmstest.chirey.mx/api/v1/login
参数:
{
“enterpriseCode”:“15770”,
“username”:“cherysh”,
“password”:“ChErY2020”
}
同步数据接口
https://dmstest.chirey.mx/dms/afterSales/api/v1/OuterAPI/repairAppointments
编码
首先封装一个获取cookie的方法到HttpUtils中:
public String getCookie() {
log.info("执行getCookie方法");
String url = dmsConfig.getLoginUrl();
HashMap<String, String> param = new HashMap<>();
param.put("enterpriseCode",dmsConfig.getEnterpriseCode());
param.put("username",dmsConfig.getUsername());
param.put("password",dmsConfig.getPassword());
String cookie = doPostJsonParamGetCookie(url, param);
// 存入redis
redisUtil.set("cookie",cookie,20*60);
log.info("cookie==="+cookie);
return cookie;
}
/**
* String url = "https://dmstest.chirey.mx/api/v1/login";
HashMap<String, String> param = new HashMap<>();
param.put("enterpriseCode","15770");
param.put("username","cherysh");
param.put("password","ChErY2020");
String s = doPostJsonParamGetCookie(url, param);
* */
public static String doPostJsonParamGetCookie(String url, Map<String, String> jsonParam) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json");
RequestConfig config = RequestConfig.custom().setConnectTimeout(20000).setConnectionRequestTimeout(20000).setSocketTimeout(20000).build();
httpPost.setConfig(config);
// 传json参数
JSONObject json = new JSONObject();
for (Map.Entry<String, String> pa : jsonParam.entrySet()) {
json.put(pa.getKey(),pa.getValue());
}
httpPost.setEntity(new StringEntity(json.toString(),"UTF-8"));
response = httpClient.execute(httpPost);
Header[] headers = response.getHeaders("Set-Cookie");
for (int i = 0; i < headers.length; i++) {
if(headers[i].toString().contains(".AspNetCore.Cookies")){
result=headers[i].toString().split("Set-Cookie: ")[1];
}
}
} catch (Exception e) {
logger.error("POST请求发送失败!url:{},异常:", url, e);
} finally {
try {
if (null != httpClient)
httpClient.close();
if (null != response)
response.close();
} catch (IOException e) {
logger.error("链接关闭失败!url:{},异常:", url, e);
}
}
return result;
}
然后封装一个同步预约单到dms的方法到HttpUtils中:
/**传jsonArray参数
[
{
"planArriveDate": "2022-06-06T00:52:12.185Z",
"appointNo": "55555",
"planArriveTime": "07:00-08:00",
"dealerCode": "18888",
"repairType": 1,
"isWx": "3",
"cellPhoneNumber": "13855222215",
"customerName": "王三",
"licensePlate": "皖B88888",
"status": 1,
"vinCode": "LVVDC21B2ND033754"
}
]
具体写法:
List<AppointBillVO> allNewBills = appointBillService.getAllNewBillListForDMS();
// 从redis获取cookie
String cookie = (String) redisUtil.get("cookie");
if(StringUtils.isEmpty(cookie)){
cookie = httpUtils.getCookie();
}
String url = "https://dmstest.chirey.mx/dms/afterSales/api/v1/OuterAPI/repairAppointments";
JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(allNewBills));
String result = HttpUtils.doPostJsonObjectParam(url, jsonArray, cookie);
* */
public static String doPostJsonObjectParam(String url, JSONArray jsonArray, String cookie) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Cookie", cookie);
httpPost.setHeader("Content-Type", "application/json");
RequestConfig config = RequestConfig.custom().setConnectTimeout(20000).setConnectionRequestTimeout(20000).setSocketTimeout(20000).build();
httpPost.setConfig(config);
// 传json参数
httpPost.setEntity(new StringEntity(jsonArray.toString(),"UTF-8"));
response = httpClient.execute(httpPost);
result = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
logger.error("POST请求发送失败!url:{},异常:", url, e);
} finally {
try {
if (null != httpClient)
httpClient.close();
if (null != response)
response.close();
} catch (IOException e) {
logger.error("链接关闭失败!url:{},异常:", url, e);
}
}
return result;
}
最后写一个定时任务接口:
// @Scheduled(cron = "0 0/10 * * * ?") // 使用xxl-job控制定时任务
@RequiredLog("APP-DMS 同步所有新建预约记录")
@ApiOperation(value = "APP-DMS 同步所有新建预约记录")
@RequestMapping(value = {"getAllNewBillListForDMS"}, method = RequestMethod.POST)
public RespMessage<List<AppointBillVO>> getAllNewBillListForDMS() {
log.info("APP-DMS 同步所有新建预约记录 定时任务调用了!!!");
// 查询所有新建预约单
List<AppointBillVO> allNewBills = appointBillService.getAllNewBillListForDMS();
log.info("查询到的所有新建预约单==="+allNewBills.toString());
// 从redis获取cookie
String cookie = (String) redisUtil.get("cookie");
log.info("从Redis获取到的cookie是==="+cookie);
if(StringUtils.isEmpty(cookie)){
cookie = httpUtils.getCookie();
}
log.info("cookie==="+cookie);
if(!CollectionUtils.isEmpty(allNewBills)){
String url = dmsConfig.getAppointmentsUrl();
JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(allNewBills));
log.info("APP-DMS 同步的所有预约记录===>"+jsonArray.toJSONString());
String result = HttpUtils.doPostJsonObjectParam(url, jsonArray, cookie);
if(result.contains("成功")){
// 将这些预约单状态修改为已发送
if(!CollectionUtils.isEmpty(allNewBills) && allNewBills.size() > 0){
ArrayList<String> appointNos = new ArrayList<>();
allNewBills.forEach(e ->{
appointNos.add(e.getAppointNo());
});
appointBillService.updateStatusByNos(appointNos);
}
return RespMessage.ok(allNewBills);
}
}
return RespMessage.errorWithMsg("同步失败");
}
HttpUtils全部代码
package com.mychery.awesomeproject.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mychery.awesomeproject.config.DmsConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Component
public class HttpUtils {
private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
//
@Autowired
private RedisUtil redisUtil;
// private JedisCluster jedisCluster;
@Autowired
private DmsConfig dmsConfig;
// @Scheduled(cron = "0 0/20 * * * ?") 使用xxl-job控制定时任务
// @Cache_Find
public String getCookie() {
log.info("执行getCookie方法");
String url = dmsConfig.getLoginUrl();
HashMap<String, String> param = new HashMap<>();
param.put("enterpriseCode",dmsConfig.getEnterpriseCode());
param.put("username",dmsConfig.getUsername());
param.put("password",dmsConfig.getPassword());
String cookie = doPostJsonParamGetCookie(url, param);
// 存入redis
redisUtil.set("cookie",cookie,20*60);
log.info("cookie==="+cookie);
return cookie;
}
/**
* String s = null;
* try {
* s = doGet(".AspNetCore.Cookies=CfDJ8F6Qt6UMPGRBiPITbV-0bZuq3vgFUiASw7A4Ud2tpKJqh4bMixXaBrEWZaGGo1ZZx6OyDzAF6EtxQP1yXyqlA-Ztfw6Mcgjg_6wrL3Ily9lNZo3aBZJguQnPuhvJQucYqppte_QI-ID-Kufu5QjVUJ-VhEXt7OtZIufHRftnDYpEb6RE4Y9cS2mLUwmFDIZkJICL5_hEb6d4xNDclfI-_WqhztjLxh9ZhflboNEyPrFVlOmvUJbxMIHV6ghbRuMX0y7WdFcRUtlkQ-Wxr_W4_Sjcmz05JeANR9MK-1x2IATxFEudwt65AP2eenQEJG_jyw; path=/; samesite=lax; httponly",
* "https://dmstest.chirey.mx/dms/afterSales/api/v1/OuterAPI/GetVehicleInfo",
* "LVTDB11B0JC005750",
* "553");
* } catch (Exception e) {
* e.printStackTrace();
* }
* System.out.println(s);
* @param cookie
* @param url
* @param vin
* @param engine
* @return
* @throws Exception
*/
public static String doGet(String cookie,String url, String vin, String engine) throws Exception {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 定义请求的参数
URI uri = new URIBuilder(url).setParameter("vin", vin).setParameter("engine", engine).build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader("Cookie",cookie);
//response 对象
CloseableHttpResponse response = null;
String resultString="0";
try {
// 执行http get请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
// System.out.println("内容长度:" + resultString);
} else {
throw new Exception("GET请求失败!");
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
return resultString;
}
/**传json对象参数
{
"enterpriseCode":"15770",
"username":"cherysh",
"password":"ChErY2020"
}
具体写法:
String url = "https://dmstest.chirey.mx/api/v1/login";
Map<String, String> param = new HashMap<>();
param.put("enterpriseCode","15770");
param.put("username","cherysh");
param.put("password","ChErY2020");
String s = doPostJsonParam(url, param);
* */
public static String doPostJsonParam(String url, Map<String, String> jsonParam) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json");
RequestConfig config = RequestConfig.custom().setConnectTimeout(20000).setConnectionRequestTimeout(20000).setSocketTimeout(20000).build();
httpPost.setConfig(config);
// 传json参数
JSONObject json = new JSONObject();
for (Map.Entry<String, String> pa : jsonParam.entrySet()) {
json.put(pa.getKey(),pa.getValue());
}
httpPost.setEntity(new StringEntity(json.toString(),"UTF-8"));
response = httpClient.execute(httpPost);
result = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
logger.error("POST请求发送失败!url:{},异常:", url, e);
} finally {
try {
if (null != httpClient)
httpClient.close();
if (null != response)
response.close();
} catch (IOException e) {
logger.error("链接关闭失败!url:{},异常:", url, e);
}
}
return result;
}
/**传jsonArray参数
[
{
"planArriveDate": "2022-06-06T00:52:12.185Z",
"appointNo": "55555",
"planArriveTime": "07:00-08:00",
"dealerCode": "18888",
"repairType": 1,
"isWx": "3",
"cellPhoneNumber": "13855222215",
"customerName": "王三",
"licensePlate": "皖B88888",
"status": 1,
"vinCode": "LVVDC21B2ND033754"
}
]
具体写法:
List<AppointBillVO> allNewBills = appointBillService.getAllNewBillListForDMS();
// 从redis获取cookie
String cookie = (String) redisUtil.get("cookie");
if(StringUtils.isEmpty(cookie)){
cookie = httpUtils.getCookie();
}
String url = "https://dmstest.chirey.mx/dms/afterSales/api/v1/OuterAPI/repairAppointments";
JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(allNewBills));
String result = HttpUtils.doPostJsonObjectParam(url, jsonArray, cookie);
* */
public static String doPostJsonObjectParam(String url, JSONArray jsonArray, String cookie) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Cookie", cookie);
httpPost.setHeader("Content-Type", "application/json");
RequestConfig config = RequestConfig.custom().setConnectTimeout(20000).setConnectionRequestTimeout(20000).setSocketTimeout(20000).build();
httpPost.setConfig(config);
// 传json参数
httpPost.setEntity(new StringEntity(jsonArray.toString(),"UTF-8"));
response = httpClient.execute(httpPost);
result = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
logger.error("POST请求发送失败!url:{},异常:", url, e);
} finally {
try {
if (null != httpClient)
httpClient.close();
if (null != response)
response.close();
} catch (IOException e) {
logger.error("链接关闭失败!url:{},异常:", url, e);
}
}
return result;
}
/**
* String url = "https://dmstest.chirey.mx/api/v1/login";
HashMap<String, String> param = new HashMap<>();
param.put("enterpriseCode","15770");
param.put("username","cherysh");
param.put("password","ChErY2020");
String s = doPostJsonParamGetCookie(url, param);
* */
public static String doPostJsonParamGetCookie(String url, Map<String, String> jsonParam) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json");
RequestConfig config = RequestConfig.custom().setConnectTimeout(20000).setConnectionRequestTimeout(20000).setSocketTimeout(20000).build();
httpPost.setConfig(config);
// 传json参数
JSONObject json = new JSONObject();
for (Map.Entry<String, String> pa : jsonParam.entrySet()) {
json.put(pa.getKey(),pa.getValue());
}
httpPost.setEntity(new StringEntity(json.toString(),"UTF-8"));
response = httpClient.execute(httpPost);
Header[] headers = response.getHeaders("Set-Cookie");
for (int i = 0; i < headers.length; i++) {
if(headers[i].toString().contains(".AspNetCore.Cookies")){
result=headers[i].toString().split("Set-Cookie: ")[1];
}
}
} catch (Exception e) {
logger.error("POST请求发送失败!url:{},异常:", url, e);
} finally {
try {
if (null != httpClient)
httpClient.close();
if (null != response)
response.close();
} catch (IOException e) {
logger.error("链接关闭失败!url:{},异常:", url, e);
}
}
return result;
}
/**
*
* @param url
* @param param
* @return
*/
public static String doPost(String url, Map<String, String> param) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try {
httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json");
RequestConfig config = RequestConfig.custom().setConnectTimeout(20000).setConnectionRequestTimeout(20000).setSocketTimeout(20000).build();
httpPost.setConfig(config);
// 传普通表单参数
List<NameValuePair> paramList = new ArrayList<>();
for (Map.Entry<String, String> pa : param.entrySet()) {
paramList.add(new BasicNameValuePair(pa.getKey(), pa.getValue()));
}
HttpEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
result = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
logger.error("POST请求发送失败!url:{},异常:", url, e);
} finally {
try {
if (null != httpClient)
httpClient.close();
if (null != response)
response.close();
} catch (IOException e) {
logger.error("链接关闭失败!url:{},异常:", url, e);
}
}
return result;
}
/**
* Post Request
*/
public static String doPost(String url, String parameterData) throws Exception {
URL localURL = new URL(url);
URLConnection connection = localURL.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterData.length()));
httpURLConnection.setConnectTimeout(30000);
httpURLConnection.setReadTimeout(30000);
OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
try {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write(parameterData.toString());
outputStreamWriter.flush();
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
reader = new BufferedReader(inputStreamReader);
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} finally {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (outputStream != null) {
outputStream.close();
}
if (reader != null) {
reader.close();
}
if (inputStreamReader != null) {
inputStreamReader.close();
}
if (inputStream != null) {
inputStream.close();
}
}
return resultBuffer.toString();
}
/**
* post请求(用于请求json格式的参数)
*/
public static String doJsonPost(String urlPath, String json) {
String result = "";
BufferedReader reader = null;
try {
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
// 设置文件类型:
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// 设置接收类型否则返回415错误
//conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型,以此来防范返回415;
conn.setRequestProperty("accept", "application/json");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
// 往服务器里面发送数据
if (StringUtils.isNotEmpty(json)) {
byte[] writebytes = json.getBytes();
// 设置文件长度
conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
OutputStream outwritestream = conn.getOutputStream();
outwritestream.write(json.getBytes());
outwritestream.flush();
outwritestream.close();
}
logger.info("http返回码:" + conn.getResponseCode());
if (conn.getResponseCode() == 200) {
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
result = reader.readLine();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}