Jackson->Jackson + HttpPost = "Invalid UTF-8 middle byte", Setting Mime and Encoding
It looks like the problem is how the ContentType
parameter for the HttpClient's StringEntity
constructor is being created.
Using the ContentType.APPLICATION_JSON
constant as a parameter (which corresponds to the "application/json; charset=utf-8" mime type) makes everything work.
Here is an example posting the JSON string to a public http service that echoes the request back to the client:
public class HttpClientEncoding {
static String TINY_UTF8_DOC = "[{ \"id\" : \"2\", \"fields\" : { \"subject\" : " +
"[{ \"name\" : \"subject\", \"value\" : \"Stra\u00DFe\" }] } }]";
public static void main(String[] args) throws IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://httpbin.org/post");
StringEntity entity = new StringEntity(TINY_UTF8_DOC, ContentType.APPLICATION_JSON);
//StringEntity entity = new StringEntity(TINY_UTF8_DOC, ContentType.create("application/json; charset=utf-8"));
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readValue(result, JsonNode.class);
System.out.println(node.get("json").get(0).get("fields").get("subject").get(0).get("value").asText());
}
}
Output:
{
"origin": "46.9.77.167",
"url": "http://httpbin.org/post",
"args": {},
"data": "[{ \"id\" : \"2\", \"fields\" : { \"subject\" : [{ \"name\" : \"subject\", \"value\" : \"Stra\u00dfe\" }] } }]",
"files": {},
"form": {},
"headers": {
"Content-Length": "90",
"User-Agent": "Apache-HttpClient/4.3.3 (java 1.5)",
"Host": "httpbin.org",
"Connection": "close",
"X-Request-Id": "c02864cc-a1d6-434c-9cff-1f6187ceb080",
"Content-Type": "application/json; charset=UTF-8"
},
"json": [
{
"id": "2",
"fields": {
"subject": [
{
"value": "Stra\u00dfe",
"name": "subject"
}
]
}
}
]
}
Straße