带有特殊字符的HttpResponse

时间:2016-03-05 14:13:01

标签: java rest http character-encoding

我为这个端点编写了一个REST客户端:

textmap.com/ethnicity_api/api

但是,在POST参数中传递名称字符串jennífer garcía,并将编码设置为UTF-8时,我得到的响应不是同一个字符串。如何在响应对象中获取相同的名称? 以下是我如何设置请求和我得到的响应:

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);

输出中名称的值为:jenn�fer garc�a

这是一个与我在请求中发送的完全不同的字符集。如何获得与我发送请求时相同的字符集?

其次,我希望相同的代码可以在Java-6和Java-7中工作。上面的代码仅使用Java-7。如何使代码适用于这两个版本?

1 个答案:

答案 0 :(得分:1)

我认为BufferedReaderbreaking the UTF8 encoding,所以这实际上与HTTP无关。另外,br可以not be needed at all

相关问题