Python发送带header的http请求

本文介绍如何利用Python的urllib2库为HTTP请求设置不同的头部信息,包括简单的User-Agent设置及更复杂的多元素头部配置。通过示例代码展示了如何发送带有特定头部的请求并获取响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单的header

import urllib2

request = urllib2.Request('http://example.com/')
request.add_header('User-Agent', 'fake-client')
response = urllib2.urlopen(request)
print request.read()

包含较多元素的header

import urllib,urllib2

url = 'http://example.com/'
headers = { 'Host':'example.com',
                    'Connection':'keep-alive',
                    'Cache-Control':'max-age=0',
                    'Accept': 'text/html, */*; q=0.01',
                    'X-Requested-With': 'XMLHttpRequest',
                    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36',
                    'DNT':'1',
                    'Referer': 'http://example.com/',
                    'Accept-Encoding': 'gzip, deflate, sdch',
                    'Accept-Language': 'zh-CN,zh;q=0.8,ja;q=0.6'
}
data = None
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
html = response.read()


<think>我们将讨论使用Python发送HTTP请求的几种方法,包括标准库和第三方库。 常见的库有:urllib (标准库), requests (第三方库), http.client (标准库底层), 以及异步的aiohttp。 这里我们重点介绍最常用的requests和urllib。 1. 使用requests库(推荐,简单易用) 2. 使用urllib(标准库,无需安装第三方包) 我们将分别给出GET和POST请求的示例。 注意:使用requests需要先安装:pip install requests</think>### Python 发送 HTTP 请求的全面指南 #### 1. 使用标准库 `urllib` ```python from urllib import request, parse # GET 请求 def get_request(url): try: with request.urlopen(url) as response: data = response.read().decode('utf-8') print(f"状态码: {response.status}") print(f"响应头: {dict(response.headers)}") return data except Exception as e: print(f"请求失败: {e}") # POST 请求(表单数据) def post_form(url, form_data): try: data = parse.urlencode(form_data).encode('utf-8') req = request.Request(url, data=data, method='POST') req.add_header('Content-Type', 'application/x-www-form-urlencoded') with request.urlopen(req) as response: return response.read().decode('utf-8') except Exception as e: print(f"请求失败: {e}") # POST 请求(JSON数据) def post_json(url, json_data): try: data = json.dumps(json_data).encode('utf-8') req = request.Request(url, data=data, method='POST') req.add_header('Content-Type', 'application/json') with request.urlopen(req) as response: return response.read().decode('utf-8') except Exception as e: print(f"请求失败: {e}") # 使用示例 if __name__ == "__main__": # GET 请求示例 print("GET 请求结果:") print(get_request("https://jsonplaceholder.typicode.com/todos/1")) # POST 表单请求示例 form_data = {'username': 'test', 'password': 'secret'} print("\nPOST 表单结果:") print(post_form("https://httpbin.org/post", form_data)) # POST JSON 请求示例 json_data = {'title': 'foo', 'body': 'bar', 'userId': 1} print("\nPOST JSON 结果:") print(post_json("https://jsonplaceholder.typicode.com/posts", json_data)) ``` #### 2. 使用第三方库 `requests`(推荐) ```python import requests # GET 请求 def get_request(url, params=None, headers=None): try: response = requests.get(url, params=params, headers=headers) response.raise_for_status() # 检查HTTP错误 print(f"状态码: {response.status_code}") print(f"响应头: {response.headers}") return response.json() # 自动解析JSON except requests.exceptions.RequestException as e: print(f"请求失败: {e}") return None # POST 请求 def post_request(url, data=None, json=None, headers=None): try: response = requests.post(url, data=data, json=json, headers=headers) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"请求失败: {e}") return None # 高级功能:会话保持、超时设置、代理等 def advanced_requests(): with requests.Session() as session: # 创建会话 session.headers.update({'User-Agent': 'MyApp/1.0'}) # 统一请求头 # 认证的请求 auth = ('user', 'pass') # 超时和代理的请求 response = session.get( 'https://api.example.com/data', auth=auth, timeout=5, # 连接超时5秒 proxies={'https': 'http://10.10.1.10:1080'} # 代理设置 ) return response.json() # 使用示例 if __name__ == "__main__": # GET 参数 params = {'userId': 1} print("GET 参数结果:") print(get_request("https://jsonplaceholder.typicode.com/todos", params=params)) # POST JSON json_data = {'title': 'foo', 'body': 'bar', 'userId': 1} print("\nPOST JSON 结果:") print(post_request("https://jsonplaceholder.typicode.com/posts", json=json_data)) # POST 表单 form_data = {'username': 'test', 'password': 'secret'} print("\nPOST 表单结果:") print(post_request("https://httpbin.org/post", data=form_data)) ``` ### 关键概念解释 1. **HTTP 方法**: - GET:获取资源(不应改变服务器状态) - POST:创建新资源 - PUT:更新资源 - DELETE:删除资源 2. **请求组件**: ```python { "method": "GET/POST/PUT/DELETE", "url": "https://api.example.com", "headers": {"Content-Type": "application/json"}, "params": {"key": "value"}, # URL查询参数 "data": "表单数据", # application/x-www-form-urlencoded "json": {"key": "value"} # application/json } ``` 3. **常见内容类型**: - `application/json`:JSON 格式数据 - `application/x-www-form-urlencoded`:表单编码数据 - `multipart/form-data`:文件上传 4. **状态码处理**: - 2xx:成功(200 OK, 201 Created) - 3xx:重定向 - 4xx:客户端错误(400 错误请求,401 未授权,404 未找到) - 5xx:服务器错误 ### 最佳实践 1. **错误处理**: ```python try: response = requests.get(url, timeout=3) response.raise_for_status() except requests.exceptions.Timeout: print("请求超时") except requests.exceptions.HTTPError as err: print(f"HTTP错误: {err.response.status_code}") except requests.exceptions.RequestException as err: print(f"其他错误: {err}") ``` 2. **性能优化**: - 使用连接池:`requests.Session()` - 设置超时:`timeout=(连接超时, 读取超时)` - 启用流式响应:`stream=True` 处理大文件 3. **安全考虑**: - 使用 HTTPS 协议 - 验证 SSL 证书(默认启用) - 敏感数据不放在 URL 中 - 使用环境变量存储凭证 4. **异步请求(aiohttp)**: ```python import aiohttp import asyncio async def fetch(session, url): async with session.get(url) as response: return await response.text() async def main(): async with aiohttp.ClientSession() as session: html = await fetch(session, 'http://python.org') print(html) asyncio.run(main()) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值