yanzhenjie / AndServer

:cherries: Web server and web framework of Android platform.
https://yanzhenjie.com/AndServer
Apache License 2.0
3.74k stars 755 forks source link

如何接受POST请求的GBK编码的中文 #528

Open HelloMaSH opened 10 months ago

HelloMaSH commented 10 months ago

作为服务端,客户端传递过来中文字符串以GBK编码,接口默认按utf-8接收到了,我如何按GBK编码获取数据呢

yanzhenjie commented 7 months ago

如果你是通过MessageConverter解析的数据,在convert方法识别客户端数据编码:

@Converter
public class AppMessageConverter implements MessageConverter {

    ...

    @Nullable
    @Override
    public <T> T convert(@NonNull InputStream stream, @Nullable MediaType mediaType, Type type) throws IOException {
        Charset charset = mediaType == null ? null : mediaType.getCharset();
        if (charset == null) {
            return JsonUtils.parseJson(IOUtils.toString(stream), type);
        }
        return JsonUtils.parseJson(IOUtils.toString(stream, charset), type);
    }
}

如果没有使用使用MessageConverter,在你api对应的方法中拿到HttpRequest后自行转换:

@RestController
class TestController {

    @RequestMapping(
        path = "/testCharset",
        method = {RequestMethod.POST},
        produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    Object testCharset(HttpRequest request) {
        ...
    }