远程调用-其他服务

本文涉及的产品
数据管理 DMS,安全协同 3个实例 3个月
推荐场景:
学生管理系统数据库
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: 远程调用-其他服务

需求

我们现在开发的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;
    }
}


目录
相关文章
|
1月前
|
XML JSON 网络协议
RPC远程服务如何调用
【2月更文挑战第12天】一个完整的 RPC 调用框架包括:通信框架、通信协议、序列化和反序列化三部分。
|
1月前
|
负载均衡 Java 网络架构
使用OpenFeign实现服务远程调用
当微服务架构日益普及,服务之间的远程调用变得至关重要。在这一背景下,OpenFeign作为一个强大的HTTP客户端框架简化了服务之间的远程通信。本文旨在介绍如何运用OpenFeign实现服务远程调用。
69 0
|
3月前
|
JSON 负载均衡 网络协议
RPC远程调用协议
RPC远程调用协议
55 0
|
3月前
|
负载均衡 前端开发 Java
openfeign远程调用的底层原理?
openfeign远程调用的底层原理?
|
3月前
|
JSON 网络协议 API
GRPC远程调用
GRPC远程调用
78 0
|
3月前
|
微服务
Feign远程调用
Feign远程调用
37 0
|
4月前
|
Java Nacos Maven
服务注册、发现和远程调用
服务注册、发现和远程调用
35 0
|
5月前
|
Nacos
openfeign远程调用
openfeign远程调用
42 0
|
9月前
|
Java Linux 微服务
Feign的远程调用--微服务重试的坑
Feign的远程调用--微服务重试的坑
272 0
|
11月前
|
消息中间件 XML JSON
一文就读懂RPC远程调用核心原理
rpc的全称是Remote Procedure Call,即远程过程调用,是分布式系统的常用通信方法。 Remote,简单来说的话就是两个不同的服务之间,两个服务肯定是两个不同的进程。因此,我们就从跨进程进行访问的角度去理解就行了。 Procedure,意思是一串可执行的代码,我们写Java的方法,就是一段课程行的代码。 Call,即调用,调用的就是跨了进程的方法。
263 0
一文就读懂RPC远程调用核心原理