0

尝试打一个休息 API 的例子,但看到 400 状态码。这是使用表单参数调用 API 的正确方法吗?

import javax.json.JsonObject;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Form;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.Response;
...
public JsonObject getUserProfile() throws Exception {
    Form userform = new Form();
    userform.param("grant_type", "password")
        .param("client_id", "cexxx")                                
        .param("username", "theuser")
        .param("password", "password")
        .param("scope", "user.read openid profile offline_access");

    Client client = ClientBuilder.newClient();

    String serverUrl = "https://login.microsoftonline.com/547xx/oauth2/v2.0/token";

    WebTarget target = client.target(serverUrl);

    final Invocation.Builder invocationBuilder = target.request();
    invocationBuilder.header("Content-Type", "application/x-www-form-urlencoded");
   
    final Response response = invocationBuilder.method(
                                    HttpMethod.POST, 
                                    Entity.entity(userform, MediaType.APPLICATION_FORM_URLENCODED), 
                                    Response.class);
    
    System.out.println("r.getStatus()=" + response.getStatus());
    ...
}

邮递员也是如此:

在此处输入图像描述

4

1 回答 1

0

感谢Giorgi的提示。

实际上,我们上面的代码以编程方式进行 API 调用是有效的。问题是我们从服务器端看到错误。

使用它,我们可以看到来自服务器的错误消息:

System.out.println(response.readEntity(String.class));

{"error":"invalid_grant","error_description":"AADSTS50034: 547..b32 目录中不存在用户帐户 sx。要登录此应用程序,必须将帐户添加到目录中。\r\nTrace ID: 4616...3c00\r\n相关 ID: 617...a01\r\n时间戳: 2020-09-29 22:25:41Z","error_codes":[50034],"timestamp":"2020- 09-29 22:25:41Z","trace_id":"461...c00","correlation_id":"617..a01","error_uri":"https://login.microsoftonline.com/error?代码=50034"}

于 2020-09-29T22:30:00.970 回答