Java POST JSON 请求中的字符编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33127780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:21:51  来源:igfitidea点击:

Character Encoding in POST JSON Request

javarestjax-rscxf

提问by Vis

I am sending a POST JSON Request to my application.

我正在向我的应用程序发送 POST JSON 请求。

POST /CharSetTest/Test HTTP/1.1
Host: localhost:8090
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 1637b92b-5896-4765-63c5-d04ad73ea9f1

{
  "SampleRequest": {
    "FullName": "関連当"
  }
}

My CXF JAXRS Consumer is defined as below.

我的 CXF JAXRS 消费者定义如下。

@POST
@Produces("application/json; charset=UTF-8")
@Consumes("application/json; charset=UTF-8")
public Response testCharSet(@Encoded String jsonBody);

But the Japanese Character (関連当) that I sent as POST request is not encoded and results in some junk characters "é¢é£???oè"

但是我作为 POST 请求发送的日语字符(关连当)没有被编码并且导致一些垃圾字符“ é¢é£???oè

Using SoapUI results in "?????" characters.

使用 SoapUI 会导致“?????” 人物。

This Junk characters differs from client to client from where I hit the request. How Could I encode my POST Request ?

这个垃圾字符从我点击请求的客户端到客户端不同。我如何编码我的 POST 请求?

回答by Rajat

Set the content-type to:

将内容类型设置为:

"application/json;charset=UTF-8" 

when sending the post request in the application you are using. You can find "content-type" in the Header of the URL in that application.

在您正在使用的应用程序中发送发布请求时。您可以在该应用程序的 URL 的标题中找到“内容类型”。

回答by Matt

None of the answers here worked for me.

这里没有一个答案对我有用。

My content-type was already set to "application/json;charset=UTF-8", but the accept-encodingsetting in my header was causing the error:

我的内容类型已经设置为“application/json;charset=UTF-8”,但是accept-encoding我的标题中的设置导致了错误:

Disable the accept-encodingsetting under Headers:

禁用accept-encoding标题下的设置:

enter image description here

在此处输入图片说明

When I deactivated the last line above, everything worked great! Hope that helps someone.

当我停用上面的最后一行时,一切都很好!希望能帮助某人。

回答by Sineth Lakshitha

Try this

尝试这个

@RequestMapping(value = "/play", method = RequestMethod.POST, produces={"application/json; charset=UTF-8"})

Set produces={"application/json; charset=UTF-8"}as above, to your @RequestMapping

produces={"application/json; charset=UTF-8"}如上设置,到你的@RequestMapping

回答by Tuncer T.

I had a similar problem and solved it bu setting HttpServletResponse instance's character encoding to utf-8 :

我遇到了类似的问题,并通过将 HttpServletResponse 实例的字符编码设置为 utf-8 来解决它:

response.setCharacterEncoding("utf-8");