【问题标题】:Consume REST API, Send data using x-www-form-urlencoded使用 REST API,使用 x-www-form-urlencoded 发送数据
【发布时间】:2019-11-07 22:28:23
【问题描述】:

我正在尝试使用 Web 服务来获取令牌。这是一个 POST 服务,我必须使用 x-www-form-urlencoded 发送数据,但我不知道该怎么做。我有以下代码,但返回错误“400 Bad Request”。我正在使用 jersey.api.client 和 gson。该服务返回一个 JSON 对象。

public VOToken getToken() {

    String uri = "https://login.mypurecloud.com/oauth/token";

    VOToken voToken = null;

    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

    System.out.println(getAuthorizationHeaderString());

    Client client = Client.create(clientConfig);
    WebResource webResource = client.resource(uri);

    Form form = new Form();
    form.add("grant_type", "client_credentials");

    WebResource.Builder builder = webResource.accept(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
    builder.header("Authorization", getAuthorizationHeaderString());
    builder.entity(form);

    //Response
    ClientResponse clientResponse = builder.type(MediaType.APPLICATION_JSON).post(ClientResponse.class);
    clientResponse.bufferEntity();
    String jsonString = clientResponse.getEntity(String.class);

    if(clientResponse.getStatus() == 200 ) {

        voToken = new Gson().fromJson(jsonString, VOToken.class);
        System.out.println(">> Access_token: "+ voToken.getAccess_token());
    }

    return voToken;
}

public String getAuthorizationHeaderString() {
    String clientId = "32ef8d9c-######################";
    String clientSecret = "6-M5A8Y06##################";
    String authorizationHeaderString = "";

    try {
        String encodedData = DatatypeConverter.printBase64Binary((clientId + ":" + clientSecret).getBytes("UTF-8"));
        authorizationHeaderString = "Basic " + encodedData;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return authorizationHeaderString;
}

【问题讨论】:

  • 谢谢你,Shankha057。现在可以正常使用了!

标签: java rest web-services jersey


【解决方案1】:

我相信是APPLICATION_FORM_URLENCODED 而不是APPLICATION_FORM_URLENCODED_TYPE
同样在您的ClientResponse 中将媒体类型更改为APPLICATION_FORM_URLENCODED

【讨论】:

    猜你喜欢
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2018-06-25
    • 2017-01-04
    • 1970-01-01
    相关资源
    最近更新 更多