|
如果你需要发送JSON数据,可以使用json参数。这会自动设置Content-Type为application/json。- import requests
- import json
- url = 'http://example.com/api/endpoint'
- data = {
- "key": "value",
- "another_key": "another_value"
- }
- headers = {'Content-Type': 'application/json'}
- response = requests.post(url, data=json.dumps(data), headers=headers)
- print(response.status_code)
- print(response.json())
复制代码 如果你需要发送表单数据,可以使用data参数。这会自动设置Content-Type为application/x-www-form-urlencoded。- import requests
- url = 'http://example.com/api/endpoint'
- data = {
- "key": "value",
- "another_key": "another_value"
- }
- response = requests.post(url, data=data)
- print(response.status_code)
- print(response.text)
复制代码
- 发送文件 (Multipart Form Data)
当你需要上传文件时,通常会使用files参数。这会设置Content-Type为multipart/form-data。- import requests
- url = 'http://example.com/api/upload'
- file = {'file': ('image.png', open('image.png', 'rb'))}
- data = {
- 'biz': 'temp',
- 'needCompress': 'true'
- }
- response = requests.post(url, data=data, files=file)
- print(response.status_code)
- print(response.text)
复制代码 如果API需要认证信息,可以在请求中添加auth参数。- import requests
- url = 'http://example.com/api/endpoint'
- username = 'your_username'
- password = 'your_password'
- response = requests.get(url, auth=(username, password))
- print(response.status_code)
- print(response.text)
复制代码 你可以选择是否允许重定向,默认情况下requests会自动处理重定向。- import requests
- url = 'http://example.com/api/endpoint'
- allow_redirects = False
- response = requests.get(url, allow_redirects=allow_redirects)
- print(response.status_code)
- print(response.history)
复制代码 你可以设置请求的超时时间,防止长时间等待响应。- import requests
- url = 'http://example.com/api/endpoint'
- timeout = 5
- try:
- response = requests.get(url, timeout=timeout)
- print(response.status_code)
- except requests.exceptions.Timeout:
- print("The request timed out")
复制代码 如果你需要发送或接收cookies,可以通过cookies参数来实现。- import requests
- url = 'http://example.com/api/endpoint'
- cookies = {'session': '1234567890'}
- response = requests.get(url, cookies=cookies)
- print(response.status_code)
- print(response.cookies)
复制代码 除了默认的头部信息外,你还可以添加自定义的头部信息。- import requests
- url = 'http://example.com/api/endpoint'
- headers = {
- 'User-Agent': 'MyApp/0.0.1',
- 'X-Custom-Header': 'My custom header value'
- }
- response = requests.get(url, headers=headers)
- print(response.status_code)
- print(response.headers)
复制代码 对于HTTPS请求,你可以指定验证证书的方式。- import requests
- url = 'https://example.com/api/endpoint'
- verify = True # 默认情况下,requests会验证SSL证书
- response = requests.get(url, verify=verify)
- print(response.status_code)
- 如果你要跳过SSL验证,可以将verify设置为False。但请注意,这样做可能会导致安全问题。
- import requests
- url = 'https://example.com/api/endpoint'
- verify = False
- response = requests.get(url, verify=verify)
- print(response.status_code)
复制代码 有时你可能需要同时上传多个文件。你可以通过传递多个files字典来实现这一点。- import requests
- url = 'http://example.com/api/upload'
- files = [
- ('file1', ('image1.png', open('image1.png', 'rb'))),
- ('file2', ('image2.png', open('image2.png', 'rb')))
- ]
- data = {
- 'biz': 'temp',
- 'needCompress': 'true'
- }
- response = requests.post(url, data=data, files=files)
- print(response.status_code)
- print(response.text)
复制代码 如果你需要通过代理服务器访问互联网,可以使用proxies参数。- import requests
- url = 'http://example.com/api/endpoint'
- proxies = {
- 'http': 'http://10.10.1.10:3128',
- 'https': 'http://10.10.1.10:1080',
- }
- response = requests.get(url, proxies=proxies)
- print(response.status_code)
复制代码 当下载大文件时,可以使用流式读取以避免内存不足的问题。- import requests
- url = 'http://example.com/largefile.zip'
- response = requests.get(url, stream=True)
- with open('largefile.zip', 'wb') as f:
- for chunk in response.iter_content(chunk_size=8192):
- if chunk:
- f.write(chunk)
复制代码 与流式下载类似,你也可以分块上传大文件以避免内存问题。- import requests
- url = 'http://example.com/api/upload'
- file_path = 'path/to/largefile.zip'
- chunk_size = 8192
- with open(file_path, 'rb') as f:
- for chunk in iter(lambda: f.read(chunk_size), b''):
- files = {'file': ('largefile.zip', chunk)}
- response = requests.post(url, files=files)
- if response.status_code != 200:
- print("Error uploading file:", response.status_code)
- break
复制代码 如果你需要多次请求同一个网站,并且希望保持状态(例如使用cookies),可以使用Session对象。- import requests
- s = requests.Session()
- # 设置session的cookies
- s.cookies['example_cookie'] = 'example_value'
- # 发送GET请求
- response = s.get('http://example.com')
- # 发送POST请求
- data = {'key': 'value'}
- response = s.post('http://example.com/post', data=data)
- print(response.status_code)
复制代码 处理网络请求时,经常会遇到各种错误。可以使用异常处理来优雅地处理这些情况。- import requests
- url = 'http://example.com/api/endpoint'
- try:
- response = requests.get(url)
- response.raise_for_status() # 如果响应状态码不是200,则抛出HTTPError异常
- except requests.exceptions.HTTPError as errh:
- print(f"Http Error: {errh}")
- except requests.exceptions.ConnectionError as errc:
- print(f"Error Connecting: {errc}")
- except requests.exceptions.Timeout as errt:
- print(f"Timeout Error: {errt}")
- except requests.exceptions.RequestException as err:
- print(f"OOps: Something Else: {err}")
复制代码 许多API使用认证令牌进行身份验证。你可以将认证令牌作为头部的一部分发送。- import requests
- url = 'http://example.com/api/endpoint'
- token = 'your_auth_token_here'
- headers = {
- 'Authorization': f'Token {token}'
- }
- response = requests.get(url, headers=headers)
- print(response.status_code)
- print(response.json())
复制代码 对于使用OAuth2的API,你需要获取一个访问令牌并将其包含在请求头中。- import requests
- # 获取OAuth2访问令牌
- token_url = 'http://example.com/oauth/token'
- data = {
- 'grant_type': 'client_credentials',
- 'client_id': 'your_client_id',
- 'client_secret': 'your_client_secret'
- }
- response = requests.post(token_url, data=data)
- access_token = response.json()['access_token']
- # 使用访问令牌进行请求
- api_url = 'http://example.com/api/endpoint'
- headers = {
- 'Authorization': f'Bearer {access_token}'
- }
- response = requests.get(api_url, headers=headers)
- print(response.status_code)
- print(response.json())
复制代码 来源:https://www.iwmyx.cn/pythondzjkqqfb.html
来源:https://www.cnblogs.com/star8521/p/18350091
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作! |
|