0


java后端对接外部系统(HttpClient HttpPost)

前言

最近遇到一个需求对接外部系统,我们自己的系统发送请求,根据请求内容的不同调用不同的外部系统。举例:我们是做互联网医院的,根据医生开处方选择药店的不同,调用各药店自己的系统,返回结果

文章对你的收货

  1. 可以学到对接外部系统的一些设计
  2. 构造需要的json
  3. java项目中HTTPPost请求外部系统或者调用url数据的三种格式
  4. 文章中的工具类代码可以直接复用

对接步骤

一般外部系统对接,都会给一份对接文档里面有接口url和请求数据以及返回结果的示例

1.先拿postman测试外部接口通不通(如图:外部系统文档中url和body)

2.postman测通以后,项目中编写请求代码,并测试

3.把外部系统的返回结果,格式化成本系统的结果集

设计思路

低耦合:本系统的类和外部系统分开,如果业务发生变化,只需修改中间类的实现就可以了。

构造json

json构造对应格式

步骤:类转换json字符串 ,json字符串在转换成Json对象
类转换json过程中,类中属性名定义的什么名称,转换完json对应的key就是什么

前置类

@Data
public class School {
    private String name;
    private String address;
    private List<Teacher> teacherList;
}
@Data
public class Teacher {
    private String name;
    private Integer age;
    private String phone;

    public Teacher(String name, Integer age, String phone) {
        this.name = name;
        this.age = age;
        this.phone = phone;
    }
}

只绑定类的属性

    /**
     * json构造:只绑定类的属性
     */
    @Test
    public void test2(){
        Teacher teacher=new Teacher("张三",28,"1827777888");
     String jsonStr = JSONObject.toJSONString(teacher);
     JSONObject jsonObjectEntity = JSONObject.parseObject(jsonStr);

     JSONObject jsonObject=new JSONObject();
     jsonObject.put("record",jsonObjectEntity);
        System.out.println(jsonObject.toString());
        //{"record":{"phone":"18279997252","name":"张三","age":28}}
    }

json 构造成数组list格式

    /**
     * json构造:构造list
     */
    @Test
    public void test3(){
        List<Teacher> list=new ArrayList<>();
        Teacher teacher=new Teacher("张三",28,"1827777888");
        Teacher teacher2=new Teacher("李四",22,"18211112222");
        list.add(teacher);list.add(teacher2);
        String jsonStr = JSONObject.toJSONString(list);
        JSONArray objects = JSONArray.parseArray(jsonStr);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("recordList",objects);
        System.out.println(jsonObject.toString());
        //{"recordList":[{"phone":"1827777888","name":"张三","age":28},{"phone":"18211112222","name":"李四","age":22}]}

    }

    /**
     * json构造:类中包含list
     */
    @Test
    public void test4(){
        School school=new School();
        school.setName("清华大学");
        school.setAddress("北京海淀");
        List<Teacher> list=new ArrayList<>();
        Teacher teacher=new Teacher("张三",28,"1827777888");
        Teacher teacher2=new Teacher("李四",22,"18211112222");
        list.add(teacher);list.add(teacher2);
        school.setTeacherList(list);

        String jsonStr = JSONObject.toJSONString(school);
        JSONObject jsonObjectSchool = JSONObject.parseObject(jsonStr);

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("record",jsonObjectSchool);
        System.out.println(jsonObject.toString());
        //{"record":{"address":"北京海淀","name":"清华大学","teacherList":[{"phone":"1827777888","name":"张三","age":28},{"phone":"18211112222","name":"李四","age":22}]}}
    }

list类中包含list

    /**
     * json构造:list类中包含list
     */
    @Test
    public void test5(){
        School school=new School();
        school.setName("清华大学");
        school.setAddress("北京海淀");
        List<Teacher> list=new ArrayList<>();
        Teacher teacher=new Teacher("张三",28,"1827777888");
        Teacher teacher2=new Teacher("李四",22,"18211112222");
        list.add(teacher);list.add(teacher2);
        school.setTeacherList(list);

        School school2=new School();
        school2.setName("北京大学");
        school2.setAddress("北京海淀");
        List<Teacher> list2=new ArrayList<>();
        Teacher teacher3=new Teacher("王五",33,"1827777888");
        Teacher teacher4=new Teacher("刘六",40,"18211112222");
        list2.add(teacher3);list2.add(teacher4);
        school2.setTeacherList(list2);
        List<School> listSchool=new ArrayList<>();
        listSchool.add(school);listSchool.add(school2);

        String jsonString = JSONObject.toJSONString(listSchool);
        JSONArray objects = JSONArray.parseArray(jsonString);
        JSONObject jsonObjectReult=new JSONObject();
        jsonObjectReult.put("schooleList",objects);
        System.out.println(jsonObjectReult.toString());
       //{"schooleList":[{"address":"北京海淀","name":"清华大学","teacherList":[{"phone":"1827777888","name":"张三","age":28},{"phone":"18211112222","name":"李四","age":22}]},{"address":"北京海淀","name":"北京大学","teacherList":[{"phone":"1827777888","name":"王五","age":33},{"phone":"18211112222","name":"刘六","age":40}]}]}
    }
//会吧实体类中为空的部分忽略掉
String jsonString = JSONObject.toJSONString(实体类);
//{"address":"北京市海淀区北坞嘉园","age":"18","datesjc":1641560533162,"name":"测试名称","sex":"男"}

//不忽略为空部分,完整转换
String jsonString2 = JSONObject.toJSONString(实体类,  SerializerFeature.WriteMapNullValue);
//{"address":"北京市海淀区北坞嘉园","age":"18","datesjc":1641560628074,"money":null,"name":"测试名称","note_seq":null,"salary":null,"sex":"男","userCourses":null}

HttpPost请求数据的三种格式

外部系统的请求格式有四种:

  1. 第一种get请求
  2. 第二种post请求 json格式的
  3. 第三种post请求 form-data表单格式
  4. 第四种post请求 x-www-form-urlencoded格式

依赖

 <!--  httpclient请求依赖 -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.7</version>
    </dependency>
            <!-- 阿里JSON解析器 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.76</version>
    </dependency>

构造json示例

        JSONObject jsonObject =new JSONObject();
        String hisPrescriptionInifoVoStr = JSONObject.toJSONString(hisPrescriptionInifoVo);
        JSONObject hisPrescriptionInifoVoJson = JSONObject.parseObject(hisPrescriptionInifoVoStr);
        jsonObject.put("record",hisPrescriptionInifoVoJson);

        String conditionListStr = JSONObject.toJSONString(conditionList);
        JSONArray conditionListJsonArray = JSONObject.parseArray(conditionListStr);
        jsonObject.put("conditionList",conditionListJsonArray);

        String paymentVoListStr = JSONObject.toJSONString(paymentVoList);
        JSONArray paymentVoListJsonArray = JSONObject.parseArray(paymentVoListStr);
        jsonObject.put("paymentList",paymentVoListJsonArray);

正常的post请求json数据格式(如图)

    //请求内容转换为 json数据字符串 (构造json字符串看上面示例)
        String body= jsonObject.toString();
        //创建一个http连接
        CloseableHttpClient client = HttpClients.createDefault();
        //创建Httppost请求
        HttpPost httpPost = new HttpPost("http://175.33.10/hisApi/saveRecipeRecord?apiId=hh4444");
        //添加头部
        httpPost.addHeader("Content-Type", "application/json");
        //请求内容格式化
        httpPost.setEntity(new StringEntity(body, "utf-8"));
        //结果返回response
        CloseableHttpResponse response = null;
        //请求流返回内容读取
        BufferedReader reader = null;
        //返回值格式化
        StringBuffer responseString = null;
        try {
            //发起请求
            response = client.execute(httpPost);
            //判断识别码200说明请求连接成功
            if (response.getStatusLine().getStatusCode() == 200) {
                reader = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent()));
                String inputLine;
                responseString = new StringBuffer();
                while ((inputLine = reader.readLine()) != null) {
                    responseString.append(inputLine);
                }
            }
        } catch (Exception e) {
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回结果转换为字符串
        String reultStr = responseString.toString();
        //返回结果转换为json对象
        JSONObject jsonObjectData = JSONObject.parseObject(reultStr);
        //返回值判断根据接口文档判断按个值是成功的标志 ,再用本系统结果集包装类R包装返回值给本系统用
        if(jsonObjectData.getString("success").contains("1")){
            return  R.ok();
        }else{
            return R.error(responseString.toString());
        }

代码请求思路: 这种表单格式的,把 表单的值都放到 url连接中,代码示例如下:

    //请求内容转换为 json数据字符串 (构造json字符串看上面示例)
        String body= jsonObject.toString();
         //因为body有中文所以要 设置utf-8
        String encode = URLEncoder.encode(body, "UTF-8");
        CloseableHttpClient client = HttpClients.createDefault();
        String tou="?client=4b9d92e8078967ae7069919793c45131&format=json&nonce=5&timestamp=1153463&signature=woith234jhsehhsdf&notes="+encode;
        HttpPost httpPost = new HttpPost("http://yyf.woxu.com:6566/order/import-template/upload-prescription"+tou);
        httpPost.addHeader("Content-Type", "application/json");
        //结果返回response
        CloseableHttpResponse response = null;
        //请求流返回内容读取
        BufferedReader reader = null;
        //返回值格式化
        StringBuffer responseString = null;
        try {
            //发起请求
            response = client.execute(httpPost);
            //判断识别码200说明请求连接成功
            if (response.getStatusLine().getStatusCode() == 200) {
                reader = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent()));
                String inputLine;
                responseString = new StringBuffer();
                while ((inputLine = reader.readLine()) != null) {
                    responseString.append(inputLine);
                }
            }
        } catch (Exception e) {
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回结果转换为字符串
        String reultStr = responseString.toString();
        //返回结果转换为json对象
        JSONObject jsonObjectData = JSONObject.parseObject(reultStr);
        //返回值判断根据接口文档判断按个值是成功的标志 ,再用本系统结果集包装类R包装返回值给本系统用
        if(jsonObjectData.getString("success").contains("1")){
            return  R.ok();
        }else{
            return R.error(responseString.toString());
        }

    //请求内容转换为 json数据字符串 (构造json字符串看上面示例)
        String body= jsonObject.toString();
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(“url地址”);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        //============== 改造成 x-www-form-urlencoded 请求格式
       SortedMap<String,String> sortedMap = null ;
        sortedMap = new TreeMap<String,String>() ;   //通过子类实例化接口对象
        sortedMap.put("jsondhy", body);//body绑定到map上 key为jsondhy就是外部系统要求的key
        //遍历map的值
        List<NameValuePair> params = new ArrayList<>();
         if (!sortedMap.isEmpty()) {
            Set<Map.Entry<String, String>> entries = sortedMap.entrySet();
            for (Map.Entry<String, String> parameter : entries) {
                BasicNameValuePair basicNameValuePair = new BasicNameValuePair(parameter.getKey(), parameter.getValue());
                params.add(basicNameValuePair);
            }
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

//结果返回response
        CloseableHttpResponse response = null;
        //请求流返回内容读取
        BufferedReader reader = null;
        //返回值格式化
        StringBuffer responseString = null;
        try {
            //发起请求
            response = client.execute(httpPost);
            //判断识别码200说明请求连接成功
            if (response.getStatusLine().getStatusCode() == 200) {
                reader = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent()));
                String inputLine;
                responseString = new StringBuffer();
                while ((inputLine = reader.readLine()) != null) {
                    responseString.append(inputLine);
                }
            }
        } catch (Exception e) {
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回结果转换为字符串
        String reultStr = responseString.toString();
        //返回结果转换为json对象
        JSONObject jsonObjectData = JSONObject.parseObject(reultStr);
        //返回值判断根据接口文档判断按个值是成功的标志 ,再用本系统结果集包装类R包装返回值给本系统用
        if(jsonObjectData.getString("success").contains("1")){
            return  R.ok();
        }else{
            return R.error(responseString.toString());
        }

get请求

get请求简单 把httppost换成httpget就可以了
HttpGet httpGet = new HttpGet(uri地址以及参数);

标签: postman 测试工具

本文转载自: https://blog.csdn.net/id_name/article/details/130300927
版权归原作者 id_name755 所有, 如有侵权,请联系我们删除。

“java后端对接外部系统(HttpClient HttpPost)”的评论:

还没有评论