[英]Bad request converting curl http request to Java
我收到以下帶有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節添加到parameters對象中,並且遇到相同的問題。 我正在使用RestTemplate,但我願意接受其他建議。
我請你幫忙。
我想問題是在curl
示例中,您在POST正文中傳遞了這些參數,而在您的Java代碼中,您使用了標頭。 嘗試將其更改為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());
您需要在以格式url編碼格式設置的請求實體中發送這些參數,並將內容類型設置為application/x-www-form-urlencoded
。
您的身體可以是一個字符串(根據您的示例):
String data = "client_id=fe37...06-566f5c762ab2&grant_type=authorization_code&client_secret=tPv..dQfqomaG&scope=mail.read&code=OAQABAAIA...gAA";
HttpEntity<String> entity = new HttpEntity<>(data);
設置內容類型標題:
headers.add("Content-Type", "application/x-www-form-urlencoded");
(實際實現取決於您使用的庫)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.