简体   繁体   中英

UTF encoding for http post using okhttp

I'm trying to post some data to a web server using OkHttp

public static void sendNewPost(NewPost post, Context context) throws IOException, NoSuchFieldException{

    RequestBody body = post.buildBody();
    URL url = buildURL("newreply.php");
    openPage(url, body, context);
}


public class NewPost {
    ...

    public setMessage(String m) {
        MESSAGE = "Probando con la letra: ñ, áéíóú";
    }

    public RequestBody buildBody() throws NoSuchFieldException{
        ...
        RequestBody postVariables = new FormBody.Builder()
            .add(MESSAGE_KEY, MESSAGE)
            .build();
        return postVariables;


    }

}

If I send that, the server will show something like this:

Probando con la letra: ñ, áéíóú

However If I change the setMessage function:

public setMessage(String m) {

    m = "Probando con la letra: ñ, áéíóú";
    MESSAGE = "";

    for (int i = 0; i < m.length(); i++) {
        switch (m.charAt(i)) {
            case 'ñ':
                MESSAGE += "%u00F1";
                break;
            case 'á':
                MESSAGE += "%u00E1";
                break;
            case 'é':
                MESSAGE += "%u00E9";
                break;
            case 'í':
                MESSAGE += "%u00ED";
                break;
            case 'ó':
                MESSAGE += "%u00F3";
                break;
            case 'ú':
                MESSAGE += "%u00FA";
                break;
            default:
                MESSAGE += m.charAt(i);
                break;
        }
    }
}

Things works as expected and the server shows the right thing. I reckon it is replacing the spanish characters for their UTF-16 codes, but I wonder if there is a better way to encode the full string, or make OkHttp handle it.

Edit: When I log the network traffic I see that, if my message is: "ññ" the browser encodes it as:

...&message=%F1%F1&...

while when I do it on android & okhttp, the message is sent as:

...&message=%C3%B1%C3%B1&...

Thats the thing I want, how to make OkHttp encode the string like the browser does.

Here's a couple of solutions that I know of:

  1. PapaParse at https://github.com/mholt/PapaParse
    • Pros: It's really lightweight
    • Cons: Don't know of any, it's always done the job for me
  2. Or, if you're already using guava or willing to take on the extra app size/method count, it has a thorough selection of parsers/delimiters/URL escapers as described in the javadoc here
    • Pros: It's got everything you could ever need for special char parsing
    • Cons: guava rarely considered useful enough in its own right to justify the extra method count it brings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM