VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • Python多种接口请求方式示例

发送JSON数据
如果你需要发送JSON数据,可以使用json参数。这会自动设置Content-Type为application/json。

highlighter- Go

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())

发送表单数据 (Form Data)
如果你需要发送表单数据,可以使用data参数。这会自动设置Content-Type为application/x-www-form-urlencoded。

highlighter- Go

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。

highlighter- Python

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参数。

highlighter- Go

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会自动处理重定向。

highlighter- Python

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)

设置超时
你可以设置请求的超时时间,防止长时间等待响应。

highlighter- Python

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,可以通过cookies参数来实现。

highlighter- Go

import requests
url = 'http://example.com/api/endpoint'
cookies = {'session': '1234567890'}
response = requests.get(url, cookies=cookies)
print(response.status_code)
print(response.cookies)

自定义Headers
除了默认的头部信息外,你还可以添加自定义的头部信息。

highlighter- Go

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)

使用SSL验证
对于HTTPS请求,你可以指定验证证书的方式。

highlighter- Python

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字典来实现这一点。

highlighter- Python

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参数。

highlighter- Go

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)

流式下载大文件
当下载大文件时,可以使用流式读取以避免内存不足的问题。

highlighter- Python

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)

分块上传大文件
与流式下载类似,你也可以分块上传大文件以避免内存问题。

highlighter- Python

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

使用Session对象
如果你需要多次请求同一个网站,并且希望保持状态(例如使用cookies),可以使用Session对象。

highlighter- Python

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)

处理错误
处理网络请求时,经常会遇到各种错误。可以使用异常处理来优雅地处理这些情况。

highlighter- Python

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使用认证令牌进行身份验证。你可以将认证令牌作为头部的一部分发送。

highlighter- Python

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认证
对于使用OAuth2的API,你需要获取一个访问令牌并将其包含在请求头中。

highlighter- Python

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


相关教程
关于我们--广告服务--免责声明--本站帮助-友情链接--版权声明--联系我们       黑ICP备17003004号-1