我通过curl 发出以下请求,可以毫无问题地与Microsoft Azure 服务进行通信。
curl --request POST https://login.microsoftonline.com/common/oauth2/v2.0/token --data 'client_id=fe37...06-566f5c762ab2&grant_type=authorization_code&client_secret=tPv..dQfqomaG&scope=mail.read&code=OAQABAAIA...gAA'
这是抛出 Bad Request 异常的 java 代码:
public String getToken(String authCode){
try {
HttpHeaders headers = new HttpHeaders();
String url = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
headers.add("client_id", "fe3..b2");
headers.add("client_secret", "tP..aG");
headers.add("grant_type", "authorization_code");
headers.add("code", authCode);
headers.add("scope", "mail.read");
HttpEntity<?> entity = new HttpEntity<>(headers);
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> response = restTemplate.exchange(builder.build().toUri(), HttpMethod.POST, entity, String.class);
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
我还尝试将 --data 部分添加到参数对象中,但遇到了同样的问题。我正在使用 RestTemplate,但我愿意接受其他建议。
我感谢你的帮助。
最佳答案
我认为问题在于,在 curl
示例中,您在 POST 正文中传递这些参数,而在 java 代码中您使用 header 。尝试将其更改为 entity
对象的主体参数的使用:
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
body.add("client_id", "fe3..b2");
// ... rest params
// Note the body object as first parameter!
HttpEntity<?> entity = new HttpEntity<Object>(body, new HttpHeaders());
关于java - 将curl http请求转换为Java的错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42098636/