【问题标题】:Bad request converting curl http request to Java将 curl http 请求转换为 Java 的错误请求
【发布时间】:2017-06-25 05:10:51
【问题描述】:

我有以下 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,但我愿意接受其他建议。

感谢您的帮助。

【问题讨论】:

    标签: java rest http curl resttemplate


    【解决方案1】:

    我想问题是在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());
    

    【讨论】:

      【解决方案2】:

      您需要将这些参数发送到格式为表单 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");
      

      (实际实现取决于你使用的库)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-17
        • 2017-12-25
        相关资源
        最近更新 更多