0

I have written a REST client for this endpoint:

textmap.com/ethnicity_api/api

However, while passing it a name string like jennífer garcía in the POST params, and setting encoding to UTF-8, the response that I get is not the same string. How to get the same name in the response object? Below is how I set the request and the response thatI get:

httpClient = HttpClients.createDefault();
httpPost = new HttpPost(baseurl);
StringEntity input = new StringEntity(inputJSON, StandardCharsets.UTF_8);
input.setContentType("application/json");
//input.setContentType("application/json; charset=UTF-8");
httpPost.setEntity(input);
response = httpClient.execute(httpPost);

if (response.getStatusLine().getStatusCode() != 200) {
    throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

output = org.apache.commons.io.IOUtils.toString(br);
System.out.println(output);

Value of the name in output is : jenn�fer garc�a

This is a completely different charset from what I had sent in the request. How can I get the same charset as I had sent in request?

Secondly, I want the same code to work in both Java-6 and Java-7. The above code is using Java-7 only. How can I make the code work for both these versions?

f_puras
  • 2,521
  • 4
  • 33
  • 38
user5917011
  • 1,137
  • 5
  • 14
  • 22
  • 1
    Try adding a `Accept-Charset` header to your POST request with it's value set to `UTF-8`. – Steve C Mar 05 '16 at 14:23
  • @SteveC doing that I get this now as output: `jennífer garcía`. STill I do not get the original string back as response :( This is the code I added: `httpPost.setHeader("Accept-Charset", "UTF-8");` – user5917011 Mar 05 '16 at 18:04
  • Can you prove that `inputJSON` is in UTF-8? – Steve C Mar 06 '16 at 12:12

1 Answers1

1

I think the BufferedReader is breaking the UTF8 encoding, so this is actually pretty unrelated to HTTP. On a side note, the br may not be needed at all.

Community
  • 1
  • 1
DaSourcerer
  • 6,288
  • 5
  • 32
  • 55