Estevao Santiago
Estevao Santiago

Reputation: 865

Post with HttpClient returns Bad Request

I am using Java, Spring boot and Apache HttpClient to try send a post request. The documentation of the resource I am trying to reach can be found here:

https://docs.enotasgw.com.br/v2/reference#incluiralterar-empresa

Below is my code:

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(incluirEmpresa);
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept", "application/json");
post.setHeader("Authorization", "Basic " + apiKey);
try {
    StringEntity entity = new StringEntity(json);
    //tried to add these two lines to see if they would fix the error, but it is the same
    entity.setContentEncoding("application/json");
    entity.setContentType("application/json");
    post.setEntity(entity);
    System.out.println(json);
    System.out.println("======================");
    CloseableHttpResponse response = httpClient.execute(post);
    System.out.println(response.getStatusLine().getReasonPhrase() + " - " + response.getStatusLine().getReasonPhrase());
    idEmpresa = response.getEntity().getContent().toString();
}

My response is 400 - Bad Request. On the interactive documentation link above, when I post my Json, I receive the error of duplicate entry, which is what I expect since the information I am sending is already on the database.

Since the interactive documentation returns the error of duplicate, I know the problem is not within my json format, but on my post request. The documentation have samples on C#, but not on Java, which is what I am using.

By the way, the json is variable is a string in case this is relevant.

Could someone try to point to me what is wrong with my post code?

Upvotes: 0

Views: 2539

Answers (1)

Estevao Santiago
Estevao Santiago

Reputation: 865

Found out what I was missing. After reviewing what was being sent to the API, i noticed the json was not in the expected format. So I did some research and found that, at least for my case, setting the headers with the content type was not enough, I also had to set the Entity that was being set to the HttpPost, to do that, i had to change this line of the code:

StringEntity entity = new StringEntity(json);

to this:

StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);

After that change, the requests started to work as expected.

Upvotes: 2

Related Questions