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

前言

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

WebClient和RestTemplate

spring5引入了 WebClient
pom配置

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

文章对你的收货

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

对接步骤

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

  1. 先拿postman测试外部接口通不通(如图:外部系统文档中url和body)
    在这里插入图片描述
  2. postman测通以后,项目中编写请求代码,并测试
  3. 把外部系统的返回结果,格式化成本系统的结果集

设计思路

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

先学习下如何构造json,查看我的另一篇(会构造的忽略)

https://blog.csdn.net/zhanghengchao123/article/details/122372149

HttpPost请求数据的三种格式

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

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

正好我对接的3个外部系统都有,下面看看这四种格式请求在代码中的实现

依赖

 <!--  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());
        }


post请求form-data表单格式 如图:

在这里插入图片描述
代码请求思路: 这种表单格式的,把 表单的值都放到 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());
        }

post请求x-www-form-urlencoded 格式 如图:

在这里插入图片描述
在这里插入图片描述
代码:

    //请求内容转换为 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地址以及参数);

如果文章帮到了你麻烦点个赞,或者评论留言你的问题

  • 8
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java后端可以使用HttpClient库来实现Post提交文件流及参数的功能。示例代码如下: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 添加文件流 builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, fileName); // 添加参数 builder.addTextBody("param1", "value1", ContentType.TEXT_PLAIN); builder.addTextBody("param2", "value2", ContentType.TEXT_PLAIN); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); CloseableHttpResponse response = httpClient.execute(httpPost); ``` 其中,`url`是要提交到的服务端地址,`file`是要提交的文件流,`fileName`是文件名。`param1`和`param2`是要提交的参数及其对应的值。 在服务端接收文件流及参数时,可以使用Spring框架的`MultipartFile`来接收文件流,使用`@RequestParam`来接收参数。示例代码如下: ```java @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("param1") String param1, @RequestParam("param2") String param2) throws IOException { byte[] bytes = file.getBytes(); // 处理文件流和参数 return "success"; } ``` 其中,`/upload`是服务端接收请求的地址,`file`是要接收的文件流,`param1`和`param2`是要接收的参数。 注意,在服务端接收参数时,需要根据参数的类型来设置参数的`ContentType`。例如,如果参数是文本类型,则设置为`ContentType.TEXT_PLAIN`。如果参数是JSON类型,则设置为`ContentType.APPLICATION_JSON`。 以上就是Java后端HttpClient Post提交文件流及参数的实现方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值