无法使用JAX-RS Invocation Builder调用带有Form参数的API,返回400状态代码

问题描述

尝试通过示例运行rest 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());
    ...
}

关于邮递员的作品:

enter image description here

解决方法

感谢Giorgi的提示。

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

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

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

{“错误”:“ invalid_grant”,“错误描述”:“ AADSTS50034:547..b32目录中不存在用户帐户sx。要登录此应用程序,必须将该帐户添加到目录。\ r \ n跟踪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?code=50034“}