springboot appelle l'interface du système B à partir du système A et obtient le résultat de retour

Il existe essentiellement 3 solutions en ligne. Mon scénario d'application actuel est relativement simple, j'ai donc choisi HttpClient.

Principalement pour l'intégrer dans le projet Springboot

1. Importer les dépendances

  <dependency>
            <groupId>org.apache.httpcomponents.client5</groupId>
            <artifactId>httpclient5</artifactId>
            <version>5.2.1</version>
 </dependency>

Deuxièmement, postez le cas de demande, portant les paramètres json pour obtenir le résultat de retour

  public void doPostTestOne() {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Post请求
        HttpPost httpPost = new HttpPost("http://10.10.123.45:8008/test/add");
        //构建post参数
        JSONObject postParam= new JSONObject();
        postParam.put("content", "参数值");
        StringEntity stringEntity = new StringEntity(postParam.toString(), ContentType.APPLICATION_JSON);
        httpPost.setEntity(stringEntity);

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态码:" + response.getCode());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                String strData = EntityUtils.toString(responseEntity);
 System.out.println("响应内容"+strData);
                 //将字符串转成对象,便于取出里面属性的值
                JSONObject jsonObject = JSONObject.parseObject(strData);
                String data = jsonObject.getString("data");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 Troisièmement, notez que EntityUtils.toString ne peut être utilisé qu'une seule fois. S'il est utilisé deux fois, une erreur sera signalée.

La raison spécifique n'est pas claire. HttpClient EntityUtils.toString(responseEntity) est converti en JSOnObject et l'erreur Stream est déjà fermée_tengyuxin's blog-CSDN blog

おすすめ

転載: blog.csdn.net/tengyuxin/article/details/132398159