问题描述
服务提供商向我提供标头数据:grant_type,Content-Type。以及正文数据:grant_type,用户名和密码。我在Postman中使用它生成OK令牌。但是在Spring应用程序中,它会生成错误HttpClientErrorException $ BadRequest:400 Bad Request。
我有可以设置正文数据的类:
c < c_crit = 1
这是设置标头数据的控制器:
T(n) = \Theta(n)
解决方法
使用类MultiValueMap和LinkedMultiValueMap可以解决问题。凭据将添加到此新对象,并与请求一起发送:
@PostMapping("/TokenGeneration")
@ResponseBody
public BodyToken TokenGeneration() throws IOException {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.set("grant_type","password");//set header data
headers.set("Content-Type","application/x-www-form-urlencoded");//set header data
MultiValueMap<String,String> body = new LinkedMultiValueMap<String,String>();//line solution
body.add("grant_type","password");//line solution
body.add("username","user");//line solution
body.add("password","123");//line solution
HttpEntity request = new HttpEntity(body,headers);//and I add this body to HttpEntity
headers.add("User-Agent","Spring's RestTemplate" );
ResponseEntity<BodyToken> response = restTemplate.exchange(
"https://sw/token",HttpMethod.POST,request,BodyToken.class
);
try {
return response.getBody();
} catch (Exception e) {
BodyToken body = new BodyToken();
log.info(e.getMessage());
return body;
}
}