springboot 从一个系统A 调用系统B得接口 并拿到返回结果

网上方案基本都是3种,我的实际应用场景比较简单,所以我选了 HttpClient

主要是将它融入到 Springboot项目里面

一、导入依赖

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

第二、post请求案例,携带json参数,获取返回结果

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

 第三、注意EntityUtils.toString只能使用一次,使用两次会报错

具体原因不清楚HttpClient EntityUtils.toString(responseEntity) 转为 JSOnObject 报错 Stream already closed_tengyuxin的博客-优快云博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@穷且益坚,不坠青云之志

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值