简体   繁体   English

如何确定HTTP响应中的内容类型

[英]How to determine the Content-Type in an HTTP Response

I'm building a web server as an exercise. 我正在构建一个Web服务器作为练习。 When I receive a raw request, it gets parsed into an simple syntax tree, and a response is built by evaluating this tree. 当我收到原始请求时,它将被解析为简单的语法树,并通过评估该树来构建响应。 My question this: When sending an HTTP Response, does the Content-Type field get set by taking the file extension of the requested resource and looking it up in a dictionary of MIME-types? 我的问题是: When sending an HTTP Response, does the Content-Type field get set by taking the file extension of the requested resource and looking it up in a dictionary of MIME-types? A good example would be the anatomy of how the response for a favicon.ico is built. 一个很好的例子是如何构造favicon.ico的响应。 Any insight into this would be most helpful. 任何对此的见解将是最有帮助的。 Thanks. 谢谢。

By default, web server looks into file extension and select what kind of Content Type it should interpret the file as. 默认情况下,Web服务器将调查文件扩展名,然后选择将其解释为哪种内容类型。 However, server-side scripting can send custom header ( eg header() function of PHP ) to override the settings . 但是,服务器端脚本可以发送自定义标头(例如PHP的header()函数)以覆盖设置。 For example, a JPEG can be interpreted as PNG if you send Content Type as image/png to web server with the following code: 例如,如果使用以下代码将Content Type作为image/png发送到Web服务器,则JPEG可以解释为PNG:

header('Content-Type: image/png');

For non-file requests, the web server looks into custom header directly. 对于非文件请求,Web服务器直接查看自定义标头。

Web server maps extension with MIME type. Web服务器使用MIME类型映射扩展名。 As you tag , Apache uses AddType directive to identify file's MIME type, while IIS and other web servers have similar settings . 在标记 ,Apache使用AddType指令来标识文件的MIME类型,而IIS和其他Web服务器具有类似的设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM