0

I am trying to make a POST request in java, and this is not working as expected.

Following this post, here is the code that I currently have

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

What I can not understand, is that while debugging this, data, is an ArrayList<NameValuePair> which the debugger shows a value of

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

Which is completely expected, where I am at a complete loss, is that after this call, the value of entity is,

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

The call has done absolutely nothing but ignore the data I passed it.

What have I done wrong here?

Edit

More Code

Caller

    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 method

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;

            ...
Community
  • 1
  • 1
Matt Clark
  • 24,947
  • 16
  • 62
  • 114

2 Answers2

1

As discussed, the reason it was not working is headers should be set directly in the request instead of entity.

So you can use something like below:

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

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

request.setEntity(entity);
Matt Clark
  • 24,947
  • 16
  • 62
  • 114
Aman Chhabra
  • 3,544
  • 1
  • 16
  • 37
0

Content-Type/Authorization are headers, so should be passed using setHeader() as suggested in comments.

update: Content-Type should be application/json instead of text/json.

Instead of UrlEncodedFormEntity/BasicNameValuePair you should use StringEntity and pass the result of your getSelection() there.

Alex Panchenko
  • 442
  • 2
  • 5