oblac / jodd

Jodd! Lightweight. Java. Zero dependencies. Use what you like.
https://jodd.org
BSD 2-Clause "Simplified" License
4.06k stars 723 forks source link

jodd-http set body encoding #761

Closed southfly closed 4 years ago

southfly commented 4 years ago
HttpRequest res = HttpRequest
                .post("https://test.hisouth.cn/http/postJson")
                .contentType("application/json;charset=utf-8")
                .charset(StringPool.UTF_8)
                .queryEncoding(StringPool.UTF_8)
                .body("{\"name\":\"你好(Chinese)\",\"age\":28}");
//                .contentTypeJson();
        String bodyText = res.send().charset(StringPool.UTF_8).bodyText();
        System.out.println(bodyText);  // {"name":"??(Chinese)","age":28}
neroux commented 4 years ago

https://oblac.github.io/jodd-site/javadoc/jodd/http/HttpBase.html#body-java.lang.String-

Sets raw body content and discards all form parameters. Important: body string is in RAW format, meaning, ISO-8859-1 encoding. Also sets "Content-Length" parameter. However, "Content-Type" is not set and it is expected from user to set this one.

You'd want to use bodyText() instead.

southfly commented 4 years ago

thanks,

        // post json
        String ram = "{\"name\":\"你好(Chinese)\",\"age\":28}";
        HttpRequest res = HttpRequest
                .post("https://test.hisouth.cn/http/postJson")
//                .contentType("application/json", StringPool.UTF_8)
//                .body(ram) // it will be convert to ISO_8859_1 always
//                .body(new String(ram.getBytes(), StringPool.ISO_8859_1))
                .bodyText(ram, "application/json", StringPool.UTF_8);
//                    .contentTypeJson();
        String bodyText = res.send().charset(StringPool.UTF_8).bodyText();
        System.out.println(bodyText); // ok, {"name":"你好(Chinese)","age":28}
        // i didn't change original charset to ISO_8859_1

for i didn't change original charset to 'ISO_8859_1' before the request send.