I have a question about OkHttp in Android and its support for character encoding, specifically using UTF-8 to support swedish characters å, ä and ö (and capitals ÅÄÖ).
The app we are building uses OkHttp to make GET and POST calls to our server system. The server runs on Tomcat behind Apache. Both Apache and Tomcat are configured to use UTF-8 character coding by default. I assume what's needed is that the http requests sent from the Android app to the server are equipped with a header containing something like "application/text; charset=utf-8".
I built this stripped-down code example to illustrate the issue. As you can see, i have included addHeader() on the request to set a header. I have also actively set a Charset on the RequestBody.
public static String testPost() throws IOException{
OkHttpClient okHttpClient = new OkHttpClient();
HttpUrl.Builder builder = new HttpUrl.Builder();
HttpUrl httpUrl = builder.scheme("https")
.host("dev.ourdomainname.com")
.addPathSegment("characterencoding")
.build();
Charset charset = Charset.forName(StandardCharsets.UTF_8.name());
RequestBody requestBody = new FormBody.Builder(charset)
.add("text", "xxåäöÅÄÖxx")
.build();
Request request = new Request.Builder()
.url(httpUrl)
.addHeader("Content-Type", "application/json; charset=utf-8")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
return "test completed";
}
At the server end, i am logging the value of the parameter named text, which comes in as "xxåäö���xx", which of course is not good enough. I also have code that loops over all headers in the request and logs them. The output looks like below. Notice how there is no "application/text; charset=utf-8" header.
DEBUG 23 Jan 14:52:37.128 - testCharacterEncoding. text: xxåäö���xx
DEBUG 23 Jan 14:52:37.129 - Header: content-type with value: application/x-www-form-urlencoded
DEBUG 23 Jan 14:52:37.129 - Header: content-length with value: 45
DEBUG 23 Jan 14:52:37.129 - Header: host with value: dev.cqrify.com
DEBUG 23 Jan 14:52:37.129 - Header: connection with value: Keep-Alive
DEBUG 23 Jan 14:52:37.129 - Header: accept-encoding with value: gzip
DEBUG 23 Jan 14:52:37.129 - Header: user-agent with value: okhttp/3.9.1
So my question is: are we doing this the wrong way? If yes, what is the right way to do it? Worst case, this could be a bug in OkHttp, but i doubt it.
For comparison, i built a simple html form to make the exact same post, and the same string sent that way comes in as "xxåäöÅÄÖxx", which is correct.
.addHeader("Content-Type", "application/json; charset=utf-8")does not match withHeader: content-type with value: application/x-www-form-urlencoded. Please elaborate, - greenapps.add("text", "xxåäöÅÄÖxx")is not ending up being compiled properly - possibly the encoding is not supported? You might try doing a System.out.println of that and see if it does print out okay - maybe this github example might help? - JGlass