2017-02-07 2 views
0

次のcurlでリクエストしても問題なくMicrosoft Azureサービスと通信できます。ここでcurl httpリクエストをJavaに変換する要求が正しくありません

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' 

は、不正な要求の例外がスローされた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を使用していますが、私は他の提案のために開いています。

私はあなたの助けをappericiate。

答えて

1

curlの例では、POSTコードの中でこれらのパラメータを渡していますが、Javaコードでは代わりにヘッダを使用しています。 entity対象の身体のparamsの使用方法に変更してみてください。

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()); 
+0

あなたは素晴らしいです! – WowBow

0

フォーム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"); 

(実際の実装は、使用ライブラリに依存)が