使用REST API,使用x-www-form-urlencoded发送数据

我正在尝试使用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;
}
leilei19870815 回答:使用REST API,使用x-www-form-urlencoded发送数据

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

本文链接:https://www.f2er.com/3141305.html

大家都在问