http - 除表单提交之外的 HTTP 请求的 MIME 类型

标签 http post http-headers put http-request

对于非 HTML 表单发送的请求,对于非文件上传,HTTP 是否将请求的 Content-Type 限制为 application/x-www-form-urlencoded,或者 MIME 类型是否“正确”/标准/语义有意义以任何其他方式?

例如,PHP自动将内容解析为$_POST,这似乎表明服务器期望x-www-form-urlencoded。另一方面,我可以使用 Ajax 在 HTTP 请求内容中发送一个 JSON 对象,并将 Content-Type 设置为 application/json。至少一些服务器技术(例如 WSGI)不会尝试解析它,而是以原始形式将其提供给脚本。

我应该在 RESTful API 的 POST 和 PUT 请求中使用什么 MIME 类型以确保符合 HTTP 的所有服务器实现?我忽略了 SOAP 和 JSON-RPC 等技术,因为它们通过 HTTP 隧道协议(protocol)而不是按预期使用 HTTP。

最佳答案

简答

您应该指定最能描述 HTTP 消息实体正文的内容类型。

长答案

For example, PHP automatically parses the content into $_POST, which seems to indicate that x-www-form-urlencoded is expected by the server.

服务器不“期待”x-www-form-urlencoded。 PHP——为了让开发人员的生活更简单——将把表单编码的实体主体解析为$_POST超全局当且仅当Content-Type: x-www- form-urlencoded 并且实体主体实际上是一个 urlencoded 键值字符串。对于带有 Content-Type: multipart/form-data 的消息,遵循类似的过程来生成 $_FILES 数组。虽然有用,但不幸的是,这些超全局变量被命名了,它们混淆了实际 HTTP 事务中真正发生的事情。

What MIME type should I use in POST and PUT requests in a RESTful API to ensure compliance with all server implementations of HTTP?

您应该指定最能描述 HTTP 消息实体主体的内容类型。始终遵守官方 HTTP 规范——如果您这样做就不会出错。来自 RFC 2616 Sec 7.2.1 (强调):

Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream".

任何主流服务器技术都会遵守这些规则。深思熟虑的 Web 应用程序不会信任您的 Content-Type header ,因为它可能正确也可能不正确。消息的发起者可以随意发送一个完全虚假的值。通常检查 Content-Type header 作为初步验证措施,但通过解析实际数据进一步验证内容。例如,如果您将 JSON 数据放入 REST 服务,端点可能首先检查以确保您已发送 Content-Type: application/json,然后实际解析实体主体确保它确实是有效的 JSON。

关于http - 除表单提交之外的 HTTP 请求的 MIME 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11911439/

相关文章:

windows - 如何从 Windows 命令行执行 HTTP HEAD 请求?

c# - 如何将用户重定向到不同的服务器并包含 HTTP 基本身份验证凭据?

javascript - 加载本地文件时出现 "Cross origin requests are only supported for HTTP."错误

C# MVC4 Jquery Ajax 发布部分 View 更新

c# - 用户代理字符串中无法识别的字符 ("")?该怎么办?

http - 状态错误 : Cannot set the body fields of a Request with content-type "application/json"

javascript - 为什么不能提交未呈现的表单?

php - 为什么 POST 和 GET 方法表单不适用于 PHP?

rest - 网络选项卡中可见的用户名和密码

ios - 要在 HTTP header 中设置的字段