UrlEncodedFormEntity 未按预期工作

UrlEncodedFormEntity not working as expected

我正在尝试在 java 中发出 POST 请求,但没有按预期工作。

this post之后,这是我目前拥有的代码

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data, Consts.UTF_8);

我无法理解的是,在调试时,data 是一个 ArrayList<NameValuePair>,调试器显示的值为

[Content-Type=text/json, Authorization=Bearer bZXL7hwy5vo7YnbiiGogKy6WTyCmioi8]

完全符合预期,但我完全不知所措的是,在这次调用之后,实体的价值是,

[Content-Type: application/x-www-form-urlencoded; charset=UTF-8,Content-Length: 78,Chunked: false]

这个调用除了忽略我传递给它的数据外什么也没做。

我做错了什么?

编辑

更多代码

来电

    String authURL = "https://api.ecobee.com/1/thermostat";
    authURL += "?format=json&body=" + getSelection();

    // request headers
    ArrayList<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
    nvps.add(new BasicNameValuePair("Content-Type", "text/json"));
    nvps.add(new BasicNameValuePair("Authorization", "Bearer " + code));

    // make the api call
    String apiResponse = HttpUtils.makeRequest(RequestMethod.POST, authURL, nvps);

makeRequest方法

public static String makeRequest(RequestMethod method, String url, ArrayList<BasicNameValuePair> data) {

    try {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpRequestBase request = null;

        switch (method) {

        case POST:

            // new post request
            request = new HttpPost(url);

            // encode the post data
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data, Consts.UTF_8); // <-- this is where I have the issue
            ((HttpPost) request).setEntity(entity);
            break;

            ...

Content-Type/Authorization 是 headers,因此应按照评论中的建议使用 setHeader() 进行传递。

更新:Content-Type 应该是 application/json 而不是 text/json.

您应该使用 StringEntity 而不是 UrlEncodedFormEntity/BasicNameValuePair 并将 getSelection() 的结果传递到那里。

正如所讨论的,它不起作用的原因是 headers 应该直接在请求中而不是在实体中设置。

因此您可以使用如下内容:

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data, Consts.UTF_8);

request.setHeader("Content-type", "application/json");
request.setHeader("Authorization","Bearer bZXL7hwy5vo7YnbiiGogKy6WTyCmioi8");

request.setEntity(entity);