声明:本文转发博客 RestTemplate POST 请求url携带参数 无法正常请求_Q z1997的博客-优快云博客
问题解决如下:
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());
总结:
我太菜了,鼓捣了一上午,才找到一个博主的文章看到解决方案;
找到了原因,特此根据自己实际情况整理一下,加深一下印象!!!