Android default charset when sending http post/put - Problems with special characters

后端 未结 4 1642

I have configured the apache httpClient like so:

HttpProtocolParams.setContentCharset(httpParameters, \"UTF-8\");
HttpProtocolParams.setHttpElementCharset(ht         


        
4条回答
  •  生来不讨喜
    2020-12-08 09:14

    Apparently, I forgot to set the StringEntity's charset to UTF-8. These lines did the trick:

        httpPut.setEntity(new StringEntity(body, HTTP.UTF_8));
        httpPost.setEntity(new StringEntity(body, HTTP.UTF_8));
    

    So, there are at least two levels to set the charset in the Android client when sending an http post with non-ascii characters.

    1. The rest client itself itself
    2. The StringEntity

    UPDATE: As Samuel pointed out in the comments, the modern way to do it is to use a ContentType, like so:

        final StringEntity se = new StringEntity(body, ContentType.APPLICATION_JSON);
        httpPut.setEntity(se);
    

提交回复
热议问题