关于Http请求头header中的Content-type问题

本文详细介绍了HTTP头部的使用方法,包括状态码、重定向等常见指令,以及如何设置内容类型、编码和缓存控制等。同时涵盖了Responses和Requests部分的相关知识。


一、header常用指令

header分为三部分:
  1. 第一部分为HTTP协议的版本(HTTP-Version);
  2. 第二部分为状态代码(Status);
  3. 第三部分为原因短语(Reason-Phrase)。
状态码

发送一个200 正常响应
header(“HTTP/1.1 200 OK”);

发送一个301 永久重定向
header(‘HTTP/1.1 301 Moved Permanently’);
页面被永久删除,可以告诉搜索引擎更新它们的urls
// set Moved Permanently header (good for redrictions)
// use with location header
header(‘HTTP/1.1 301 Moved Permanently’);
告诉浏览器要获取的内容还没有更新
// header for telling the browser that the content
// did not get changed
header(‘HTTP/1.1 304 Not Modified’);

访问受限
header(‘HTTP/1.1 403 Forbidden’);
发送一个404 找不到资源响应
header(‘HTTP/1.1 404 Not Found’);

服务器错误
header(‘HTTP/1.1 500 Internal Server Error’);
发送一个503 网站暂时不能访问
header(‘HTTP/1.1 503 Service Temporarily Unavailable’);

重定向到一个新的位置

// redirect to a new location:
header(‘Location: http://www.example.org/’);
延迟一段时间后重定向
// redrict with delay:
header(‘Refresh: 10; url=http://www.example.org/’);
print ‘You will be redirected in 10 seconds’;

覆盖 X-Powered-By value

// override X-Powered-By: PHP:
header(‘X-Powered-By: PHP/4.4.0’);
header(‘X-Powered-By: Brain/0.6b’);

内容语言 (en = English)

// content language (en = English)
header(‘Content-language: en’);

最后修改时间(在缓存的时候可以用到)

// last modified (good for caching)
t i m e = t i m e ( ) − 60 ; / / o r f i l e m t i m e ( time = time() - 60; // or filemtime( time=time()60;//orfilemtime(fn), etc
header(‘Last-Modified: ‘.gmdate(‘D, d M Y H:i:s’, $time).’ GMT’);

设置内容的长度 (缓存的时候可以用到):

// set content length (good for caching):
header(‘Content-Length: 1234’);

用来下载文件:

// Headers for an download:
header(‘Content-Type: application/octet-stream’); header(‘Content-Disposition: attachment; filename=“example.zip”’);
header(‘Content-Transfer-Encoding: binary’);

禁止缓存当前文档:

// load the file to send:readfile(‘example.zip’);
// Disable caching of the current document:
header(‘Cache-Control: no-cache, no-store, max-age=0, must-revalidate’);
header(‘Expires: Mon, 26 Jul 1997 05:00:00 GMT’);

设置内容类型:

// Date in the pastheader(‘Pragma: no-cache’);
// set content type:
header(‘Content-Type: text/html; charset=iso-8859-1’);
header(‘Content-Type: text/html; charset=utf-8’);

header(‘Content-Type: text/plain’); // plain text file
header(‘Content-Type: image/jpeg’); // JPG picture
header(‘Content-Type: application/zip’); // ZIP file
header(‘Content-Type: application/pdf’); // PDF file
header(‘Content-Type: audio/mpeg’); // Audio MPEG (MP3,…) file
header(‘Content-Type: application/x-shockwave-flash’); // Flash animation

显示登录对话框,可以用来进行HTTP认证

// show sign in box
header(‘HTTP/1.1 401 Unauthorized’);
header(‘WWW-Authenticate: Basic realm=“Top Secret”’);
print 'Text that will be displayed if the user hits cancel or ';

网页重定向

header(‘Location: http://www.php-chongqing.com/’);
设置网页3秒后重定向
header(‘Refresh: 3; url=http://www.php-chongqing.com/’);
echo ‘网页将在3秒后跳转到http://www.php-chongqing.com’;

设置网页编码

header(‘Content-Type: text/html; charset=utf-8’);

设置网页输出

设置网页输出一个图片流
header(‘Content-Type: image/jpeg’);
设置网页输出一个pdf文档
header(‘Content-Type: application/pdf’);
设置网页输出一个zip文档
header(‘Content-Type: application/zip’);

二、Responses 部分

Headercentered解释right-aligned 示例
Accept-Ranges表明服务器是否支持指定范围请求及哪种类型的分段请求Accept-Ranges: bytes
Age从原始服务器到代理缓存形成的估算时间(以秒计,非负)Age: 12
Allow对某网络资源的有效的请求行为,不允许则返回405Allow: GET, HEAD
Cache-Control告诉所有的缓存机制是否可以缓存及哪种类型Cache-Control: no-cache
Content-Encodingweb服务器支持的返回内容压缩编码类型。Content-Encoding: gzip
Content-Language响应体的语言Content-Language: en,zh
Content-Length响应体的长度Content-Length: 348
Content-Location请求资源可替代的备用的另一地址Content-Location: /index.htm
Content-MD5返回资源的MD5校验值Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==
Content-Range在整个返回体中本部分的字节位置Content-Range: bytes 21010-47021/47022
Content-Type返回内容的MIME类型Content-Type: text/html; charset=utf-8
Date原始服务器消息发出的时间Date: Tue, 15 Nov 2010 08:12:31 GMT
ETag请求变量的实体标签的当前值ETag: “737060cd8c284d8af7ad3082f209582d”
Expires响应过期的日期和时间Expires: Thu, 01 Dec 2010 16:00:00 GMT
Last-Modified请求资源的最后修改时间Last-Modified: Tue, 15 Nov 2010 12:45:26 GMT
Location用来重定向接收方到非请求URL的位置来完成请求或标识新的资源Location: http://www.zcmhi.com/archives/94.html
Pragma包括实现特定的指令,它可应用到响应链上的任何接收方Pragma: no-cache
Proxy-Authenticate它指出认证方案和可应用到代理的该URL上的参数Proxy-Authenticate: Basic
refresh应用于重定向或一个新的资源被创造,在5秒之后重定向(由网景提出,被大部分浏览器支持)Refresh: 5; url=http://www.zcmhi.com/archives/94.html
Retry-After如果实体暂时不可取,通知客户端在指定时间之后再次尝试Retry-After: 120
Serverweb服务器软件名称Server: Apache/1.3.27 (Unix) (Red-Hat/Linux)
Set-Cookie设置Http CookieSet-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1
Trailer指出头域在分块传输编码的尾部存在Trailer: Max-Forwards
Transfer-Encoding文件传输编码Transfer-Encoding:chunked
Vary告诉下游代理是使用缓存响应还是从原始服务器请求Vary: *
Via告知代理客户端响应是通过哪里发送的Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
Warning警告实体可能存在的问题Warning: 199 Miscellaneous warning
WWW-Authenticate表明客户端请求实体应该使用的授权方案WWW-Authenticate: Basic
Content-Type请求的与实体对应的MIME信息Content-Type: application/x-www-form-urlencoded
Date请求发送的日期和时间Date: Tue, 15 Nov 2010 08:12:31 GMT
Expect请求的特定的服务器行为Expect: 100-continue
From发出请求的用户的EmailFrom: user@email.com
Host指定请求的服务器的域名和端口号Host: www.zcmhi.com
If-Match只有请求内容与实体相匹配才有效If-Match: “737060cd8c284d8af7ad3082f209582d”
If-Modified-Since如果请求的部分在指定时间之后被修改则请求成功,未被修改则返回304代码If-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT
If-None-Match如果内容未改变返回304代码,参数为服务器先前发送的Etag,与服务器回应的Etag比较判断是否改变If-None-Match: “737060cd8c284d8af7ad3082f209582d”
If-Range如果实体未改变,服务器发送客户端丢失的部分,否则发送整个实体。参数也为EtagIf-Range: “737060cd8c284d8af7ad3082f209582d”
If-Unmodified-Since只在实体在指定时间之后未被修改才请求成功If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT
Max-Forwards限制信息通过代理和网关传送的时间Max-Forwards: 10
Pragma用来包含实现特定的指令Pragma: no-cache
Proxy-Authorization连接到代理的授权证书Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Range只请求实体的一部分,指定范围Range: bytes=500-999
Referer先前网页的地址,当前请求网页紧随其后,即来路Referer: http://www.zcmhi.com/archives/71.html
TE客户端愿意接受的传输编码,并通知服务器接受接受尾加头信息TE: trailers,deflate;q=0.5
Upgrade向服务器指定某种传输协议以便服务器进行转换(如果支持)Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11
User-AgentUser-Agent的内容包含发出请求的用户信息User-Agent: Mozilla/5.0 (Linux; X11)
Via通知中间网关或代理服务器地址,通信协议Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
Warning关于消息实体的警告信息Warn: 199 Miscellaneous warning

三、 Requests部分

Header解释示例
Accept指定客户端能够接收的内容类型Accept: text/plain, text/html
Accept-Charset浏览器可以接受的字符编码集。Accept-Charset: iso-8859-5
Accept-Encoding指定浏览器可以支持的web服务器返回内容压缩编码类型。Accept-Encoding: compress, gzip
Accept-Language浏览器可接受的语言Accept-Language: en,zh
Accept-Ranges可以请求网页实体的一个或者多个子范围字段Accept-Ranges: bytes
AuthorizationHTTP授权的授权证书Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Cache-Control指定请求和响应遵循的缓存机制Cache-Control: no-cache
Connection表示是否需要持久连接。(HTTP 1.1默认进行持久连接)Connection: close
CookieHTTP请求发送时,会把保存在该请求域名下的所有cookie值一起发送给web服务器。Cookie: $Version=1; Skin=new;
Content-Length请求的内容长度Content-Length: 348

content-type补充

在这里插入图片描述
规范:只要Content-Type设置为application/json的时候,前台的data要传递String字符串

ajax设置了contentType 为json的话,以后就养成习惯,必须发字符串

<think>首先,用户在询问关于设置HTTP头部中Content-Type的相关信息。他们特别提到了"header头中content-type的设置方法"。我需要参考提供的引用,但它们只是参考,我应该更多地基于用户的查询。 引用[1]讨论了在@RequestMapping注解中使用headers来设置Content-Type,这看起来像是Spring框架中的内容。引用[2]讨论了PHP中的header()函数。 用户的问题是通用的:"header头中content-type的设置方法"。所以,我应该提供一个通用的解释,涵盖常见的设置方法,而不局限于特定框架。 关键点: - 设置Content-Type的方法取决于上下文:比如在服务器端(如PHP、Java Spring)、客户端(如JavaScript fetch API)、或直接在HTTP请求中。 - 我需要解释什么是Content-Type:它指定了HTTP消息体的MIME类型,例如application/json、text/html等。 基于系统指令: - 所有行内数学表达式使用$...$,但在这个上下文中,可能没有数学内容,所以可能不需要。 - 独立公式使用$$...$$,但同样,这里可能不适用。 - LaTeX语法正确 – 如果有数学,但我预计没有。 - 使用中文回答 – 整个响应必须是中文。 - 生成相关问题 – 在最后,我需要添加相关问题- 引用的段落末尾自然地添加引用标识 – 我使用了引用[1]和[2],所以应该在结束时添加 [^1] 和 [^2]。 响应结构: - 清晰的结构:介绍、方法、总结。 - 帮助用户逐步解决问题:解释什么是Content-Type,然后如何设置它。 - 真实可靠:基于标准HTTP知识。 通用设置方法: 1. **在服务器端设置:** - PHP: 使用header()函数,如header("Content-Type: application/json"); - Java (Spring): 使用@RequestMapping的headers属性或直接设置响应头。 - Node.js: 使用Express的res.set('Content-Type', 'application/json')或res.json()。 - Python Flask: 使用response.headers['Content-Type'] = 'application/json'。 2. **在客户端设置:** - JavaScript Fetch API: 在请求头中设置,如fetch(url, { headers: { 'Content-Type': 'application/json' } }); - XMLHttpRequest: 类似地设置请求头。 3. **在HTTP请求中:** - 当发送请求时,在Header部分指定Content-Type。 引用用户提供的引用: - 引用[1]提到了Spring中的设置方法。 - 引用[2]提到了PHP中的header()函数。 - 我应该自然地集成这些。 响应大纲: 1. 介绍Content-Type的作用。 2. 解释设置方法: - 在服务器端(PHP、Spring示例)。 - 在客户端(Fetch API示例)。 3. 总结。 4. 添加相关问题。 相关问题生成: -Content-Type相关的扩展问题,如常见MIME类型、如何选择Content-Type等。 最后结尾添加引用标识:在引用内容的末尾添加 [^1] 或 [^2]。 确保语言是中文。 </think>### HTTP头部中Content-Type的设置方法 Content-TypeHTTP头部中的一个关键字段,它指定了HTTP消息体(如请求体或响应体)的媒体类型(MIME类型),例如`application/json`表示JSON数据、`text/html`表示HTML页面等。设置Content-Type的正确性至关重要,因为它能确保客户端和服务器正确解析数据,避免格式错误或兼容性问题。设置方法因上下文而异(服务器端、客户端或直接在HTTP请求中),下面我将逐步解释常见场景下的设置方法。 #### 1. **服务器端设置Content-Type** 在服务器端编程中,通常需要在生成HTTP响应时设置Content-Type头。以下是主流语言和框架的示例: - **PHP**:使用`header()`函数直接设置响应头。例如,设置JSON类型响应: ```php <?php header("Content-Type: application/json"); // 设置Content-Type为JSON echo json_encode(['message' => 'Hello, World!']); // 发送JSON数据 ?> ``` 这种方法简单高效,适用于动态网页生成[^2]。 - **Java Spring框架**:在Spring MVC中,可以使用`@RequestMapping`注解的`headers`属性来指定Content-Type条件或直接设置响应头。例如: ```java @RestController public class MyController { @RequestMapping(value = "/data", headers = {"Content-Type=application/json"}) // 要求请求头匹配JSON类型 public ResponseEntity<String> getData() { return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body("{\"key\":\"value\"}"); // 设置响应Content-Type } } ``` 这里,`headers`属性可以用于过滤请求,而`contentType()`方法直接设置响应头的Content-Type字段[^1]。 - **Node.js (Express)**:使用`res.set()`或`res.type()`方法: ```javascript const express = require('express'); const app = express(); app.get('/api', (req, res) => { res.set('Content-Type', 'application/json'); // 设置Content-Type头 res.json({ data: 'example' }); // Express自动设置JSON类型 }); app.listen(3000); ``` - **Python Flask**:通过修改响应对象的头部: ```python from flask import Flask, Response app = Flask(__name__) @app.route('/') def home(): response = Response('{"message": "Hello"}', content_type='application/json') # 直接设置Content-Type return response ``` **关键提示**:服务器端设置时,确保在所有内容输出前设置头信息,否则可能导致错误。例如在PHP中,`header()`函数必须在任何HTML输出前调用[^2]。 #### 2. **客户端设置Content-Type** 在客户端脚本中(如浏览器JavaScript),通常需要在发送HTTP请求时设置Content-Type头。这在AJAX调用或Fetch API中很常见: - **JavaScript Fetch API**:在HTTP请求的headers选项中指定: ```javascript fetch('https://example.com/api', { method: 'POST', headers: { 'Content-Type': 'application/json' // 设置请求头Content-Type }, body: JSON.stringify({ name: 'John' }) // 请求体数据 }) .then(response => response.json()) .then(data => console.log(data)); ``` - **XMLHttpRequest**:使用`setRequestHeader()`方法: ```javascript const xhr = new XMLHttpRequest(); xhr.open('POST', 'https://example.com/api'); xhr.setRequestHeader('Content-Type', 'application/json'); // 设置Content-Type xhr.send(JSON.stringify({ id: 1 })); ``` **注意事项**:客户端的Content-Type必须与请求体格式一致。例如,如果发送JSON数据,Content-Type应为`application/json`;如果发送表单数据,则设置为`application/x-www-form-urlencoded`或`multipart/form-data`。 #### 3. **直接在HTTP请求中设置** 在手动发送HTTP请求时(如使用curl或Postman),可以直接在Header部分指定Content-Type- **curl命令**: ```bash curl -X POST https://example.com/api \ -H "Content-Type: application/json" \ # 设置Header -d '{"key": "value"}' # 请求体 ``` - **浏览器开发者工具**:在Network面板中查看或修改请求头。 #### 总结 设置Content-Type的核心是明确媒体类型(MIME类型),常用值包括`application/json`、`text/html`、`image/png`等。设置方法取决于: - **服务器端**:使用框架特定函数(如PHP的`header()`或Spring的注解)。 - **客户端**:在请求头中明确指定。 - **通用原则**:始终确保Content-Type与消息体格式匹配,否则可能引发解析错误(如400 Bad Request)。如需详细MIME类型列表,可以参考HTTP标准文档[^2]。 如果您有具体场景(如某个编程语言),可以提供更多细节,我会给出针对性建议。 相关问题: 1. Content-Type的值有哪些常见类型?如何选择合适的MIME类型? 2. 设置Content-Type时常见的错误有哪些?如何避免? 3. HTTP头中其他常用字段有哪些?例如Accept或Authorization的作用是什么?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值