使用requests请求返回401,但urllib3与curl可正常访问的问题
问题:使用requests发送POST请求返回401未授权,但urllib3和curl可正常访问
可行的urllib3代码
import urllib3 import json # Initialize a PoolManager instance http = urllib3.PoolManager() # Define the URL, headers, and data url = "https://<url>" headers = { "Authorization": "Bearer <token>", "Content-Type": "application/json; charset=utf-8" } data = { "name": "some_test" } # Encode data to JSON encoded_data = json.dumps(data).encode('utf-8') # Send the POST request response = http.request( 'POST', url, body=encoded_data, headers=headers ) # Print the response status and data print(response.status) print(response.data.decode('utf-8'))
可行的curl命令
curl -X "POST" "https://<url>" \ -H 'Authorization: Bearer <token>' \ -H 'Content-Type: application/json; charset=utf-8' \ -d $'{ "name": "some_test" }'
报错的requests代码
import requests url = "<url>" headers = { "Authorization": "Bearer <token>", "Content-Type": "application/json; charset=utf-8" } data = { "name": "some_test" } response = requests.post(url, headers=headers, json=data) print(response.status_code) print(response.text)
问题排查与解决方法
检查URL完整性:你的requests代码中
url = "<url>"缺少https://前缀,而urllib3和curl的URL都包含该前缀。如果目标服务器强制HTTPS,不带前缀的URL可能触发HTTP重定向,导致Authorization头部丢失,引发401错误。修正URL为"https://<url>"后重试。避免重复设置Content-Type:使用
requests.post(..., json=data)时,requests会自动添加Content-Type: application/json头部,手动添加的头部可能和自动生成的存在格式差异(比如字符集声明)。可以移除手动设置的Content-Type,让requests自动处理:import requests url = "https://<url>" headers = { "Authorization": "Bearer <token>" } data = { "name": "some_test" } response = requests.post(url, headers=headers, json=data)手动编码JSON,复刻urllib3请求:完全对齐urllib3的请求方式,手动编码JSON数据并通过
data参数传递,确保请求内容和urllib3完全一致:import requests import json url = "https://<url>" headers = { "Authorization": "Bearer <token>", "Content-Type": "application/json; charset=utf-8" } data = { "name": "some_test" } encoded_data = json.dumps(data).encode('utf-8') response = requests.post(url, headers=headers, data=encoded_data)禁用自动重定向:如果服务器存在重定向,requests默认会自动跟随,可能导致Authorization头部在重定向请求中丢失。添加
allow_redirects=False参数测试:response = requests.post(url, headers=headers, json=data, allow_redirects=False)
内容的提问来源于stack exchange,提问作者doom4
相关产品推荐
相关产品推荐

