在python中使用httpx时请求失败,但使用Request成功

问题描述 投票:0回答:1

我尝试使用 httpx 发送 api 请求,但失败了。 当我尝试使用 request 发送相同的请求时,它工作正常。 这可能是什么原因造成的?

使用请求

import requests

headers = {
    'accept-language': 'en-US',
    'content-type': 'application/json',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
}

response = requests.get('https://www.unibet.com/sportsbook-feeds/views/filter/baseball/all/matches', headers=headers)

print(response.status_code)

输出200

使用httpx:

import httpx

headers = {
    'accept-language': 'en-US',
    'content-type': 'application/json',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
}

response = httpx.get('https://www.unibet.com/sportsbook-feeds/views/filter/baseball/all/matches', headers=headers)

print(response.status_code)

输出503

我尝试过的:

我的猜测是 httpx 默认某些查询参数的方式与 request 不同。我尝试在每一侧以相同的方式设置所有参数,但没有成功。

url = 'https://www.unibet.com/sportsbook-feeds/views/filter/basketball/all/matches', 
        method = 'GET', 
        headers = headers,
        params = None,
        data = None,
        files = None,
        json = None,
        cookies = None,
        auth = None,
        timeout = None
python request request-headers httpx
1个回答
0
投票

感谢 chitown 83,我找到了问题的解决方案。

HTTPx 的证书似乎有问题。我能够通过使用下面的代码示例为我的客户端分配默认上下文来解决我的问题。

import httpx, ssl, certifi
context = ssl.create_default_context()
context.load_verify_locations(certifi.where()) 
client = httpx.Client(verify=context)  
client.get('https://example.com')
© www.soinside.com 2019 - 2024. All rights reserved.