RestTemplate POST请求 URL携带参数

声明:本文转发博客 RestTemplate POST 请求url携带参数 无法正常请求_Q z1997的博客-CSDN博客

问题解决如下

1、对接第三方的时候,有一个接口是post请求,但是参数是拼接在url中;

2、使用postman请求,返回结果正常如图:

 3、在springboot项目中使用RestTemplate 直接拼接参数请求报错,结果如图:

 

        RestTemplate restTemplate = new RestTemplate();
        // 1.设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        //传递请求体时必须设置传递参数的格式,为Content-Type : application/json
        httpHeaders.add("Content-Type", "application/x-www-form-urlencoded");
        // 2.请求头 & 请求体
        HttpEntity<String> httpEntity = new HttpEntity("", httpHeaders);
        // 拼接地址
        String tokenUrl = "http://xxxx:9081/nccloud/opm/accesstoken";
        StringBuilder sb = new StringBuilder();
        sb.append(tokenUrl);
        sb.append("?");
        sb.append("biz_center=" + "1");
        sb.append("&grant_type=" + "client_credentials");


        String url = sb.toString();
        System.out.println("请求URL: " + url);
        //返回类型,如果不确定返回类型,使用String接受,用fastjson处理Json字符串
        ResponseEntity<String> responseEntity = restTemplate.exchange(
                url ,
                HttpMethod.POST,
                httpEntity,
                String.class);
        System.out.println("返回信息 333333: " + responseEntity.getBody());

 

4、解决:将拼接后的地址重新生成一个URI对象,然后传入RestTemplate 调用即可

 

        RestTemplate restTemplate = new RestTemplate();
        // 1.设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        //传递请求体时必须设置传递参数的格式,为Content-Type : application/json
        httpHeaders.add("Content-Type", "application/x-www-form-urlencoded");
        // 2.请求头 & 请求体
        HttpEntity<String> httpEntity = new HttpEntity("", httpHeaders);

        String tokenUrl = "http://222.173.167.206:9081/nccloud/opm/accesstoken";
        StringBuilder sb = new StringBuilder();
        sb.append(tokenUrl);
        sb.append("?");
        sb.append("biz_center=" + "1");
        String url = sb.toString();
        System.out.println("请求URL: " + url);

        URI uri_token = new URI(url);

        //返回类型,如果不确定返回类型,使用String接受,用fastjson处理Json字符串
        ResponseEntity<String> responseEntity = restTemplate.exchange(
                uri_token,
                HttpMethod.POST,
                httpEntity,
                String.class);
        System.out.println("返回信息 333333: " + responseEntity.getBody());

总结:

我太菜了,鼓捣了一上午,才找到一个博主的文章看到解决方案;

找到了原因,特此根据自己实际情况整理一下,加深一下印象!!!

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值