Search code examples
httppostserializationapache-commons-httpclient

Apache HttpResponse when sending unusual characters in body (POST verb)


i got something like that :

(using : org.apache.http.HttpResponse)

String jsondata = "{\"issuerName\": \"Sarl.\"}";

try {
  httpPost.setHeader(getAuthorizationHeader(LOGIN_KEY));
  StringEntity jsonparam = null;
  jsonparam = new StringEntity(jsondata);
  jsonparam.setChunked(true);
  httpPost.addHeader("content-type", "application/json;charset=UTF-8");

  httpPost.setEntity(jsonparam);
  response = httpClient.execute(httpPost);

  if (response.getStatusLine().getStatusCode() == 200) {
  // some code 

all is fine in this case, with the payload Sarl. BUT, if i replace

String jsondata = "{\"issuerName\": \"Sarl.\"}";

by

String jsondata = "{\"issuerName\": \"Sàrl.\"}";

the serialization doesn't seem to be correct, as remote API never respond in 200 (it works well with Postman, with the same payload.

Does anybody has an idea ?


Solution

  • You'll need to specify UTF-8 for your StringEntity, i.e.

    jsonparam = new StringEntity(jsondata, "UTF-8");
    

    You may also need to set the Accept-Encoding HTTP header for UTF-8, i.e.

    httpPost.setHeader("Accept-Encoding", "UTF-8");