“Content-type: application/json;"是什么意思?字符集=utf-8"实际意思? [英] What does "Content-type: application/json; charset=utf-8" really mean?

查看:128
本文介绍了“Content-type: application/json;"是什么意思?字符集=utf-8"实际意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我向 REST 服务发出带有 JSON 正文的 POST 请求时,我包含 Content-type: application/json;charset=utf-8 在消息头中.如果没有此标头,我会从服务中收到错误消息.我也可以在没有 ;charset=utf-8 部分的情况下成功使用 Content-type: application/json .

When I make a POST request with a JSON body to my REST service I include Content-type: application/json; charset=utf-8 in the message header. Without this header, I get an error from the service. I can also successfully use Content-type: application/json without the ;charset=utf-8 portion.

charset=utf-8 到底做了什么?我知道它指定了字符编码,但没有它服务也能正常工作.这种编码是否限制了消息正文中可以包含的字符?

What exactly does charset=utf-8 do ? I know it specifies the character encoding but the service works fine without it. Does this encoding limit the characters that can be in the message body?

推荐答案

标题只是表示内容的编码方式.不一定可以从内容本身推断出内容的类型,即你不能不一定只是看看内容,并知道如何处理它.这就是 HTTP 标头的用途,它们告诉接收者他们(据说)正在处理什么样的内容.

The header just denotes what the content is encoded in. It is not necessarily possible to deduce the type of the content from the content itself, i.e. you can't necessarily just look at the content and know what to do with it. That's what HTTP headers are for, they tell the recipient what kind of content they're (supposedly) dealing with.

内容类型:application/json;charset=utf-8 指定内容为JSON格式,UTF-8字符编码.指定编码对于 JSON 来说有些多余,因为 JSON 的默认(仅?)编码是 UTF-8.因此,在这种情况下,接收服务器显然很高兴知道它正在处理 JSON 并假设默认情况下编码为 UTF-8,这就是它可以使用或不使用标头的原因.

Content-type: application/json; charset=utf-8 designates the content to be in JSON format, encoded in the UTF-8 character encoding. Designating the encoding is somewhat redundant for JSON, since the default (only?) encoding for JSON is UTF-8. So in this case the receiving server apparently is happy knowing that it's dealing with JSON and assumes that the encoding is UTF-8 by default, that's why it works with or without the header.

这种编码是否限制了消息正文中可以包含的字符?

Does this encoding limit the characters that can be in the message body?

没有.您可以在标题和正文中发送任何您想要的内容.但是,如果两者不匹配,您可能会得到错误的结果.如果您在标头中指定内容是 UTF-8 编码的,但您实际上发送的是 Latin1 编码的内容,则接收方可能会产生垃圾数据,试图将 Latin1 编码的数据解释为 UTF-8.当然,如果您指定要发送 Latin1 编码的数据并且您确实在这样做,那么是的,您只能使用 Latin1 编码的 256 个字符.

No. You can send anything you want in the header and the body. But, if the two don't match, you may get wrong results. If you specify in the header that the content is UTF-8 encoded but you're actually sending Latin1 encoded content, the receiver may produce garbage data, trying to interpret Latin1 encoded data as UTF-8. If of course you specify that you're sending Latin1 encoded data and you're actually doing so, then yes, you're limited to the 256 characters you can encode in Latin1.

这篇关于“Content-type: application/json;"是什么意思?字符集=utf-8"实际意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆