如何将 headers 传递给与 session.get() 异步
how to pass headers to async with session.get()
我想知道如何在下面的get调用中传递header
headers = {
'User-Agent': 'Mozilla'
}
async def fetch(url, session):
async with session.get(url) as response:
resp = await response.read()
return resp
我尝试了以下但没有得到任何回应。
headers = {
'User-Agent': 'Mozilla'
}
async def fetch(url, session):
async with session.get(url, headers=headers) as response:
resp = await response.read()
return resp
objective是异步调用不同的url。需要知道是否还有其他替代方法,但无论如何,都需要通过 headers 才能获得正确的响应。
您可以对请求使用 httpbin.org 以查看服务器如何看待您的请求:
import asyncio
import aiohttp
from pprint import pprint
headers = {
'User-Agent': 'Mozilla'
}
async def fetch(url, session):
async with session.get(url, headers=headers) as response:
res = await response.json()
pprint(res)
async def main():
async with aiohttp.ClientSession() as session:
await fetch("http://httpbin.org/get", session)
asyncio.run(main())
结果:
{'args': {},
'headers': {'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Host': 'httpbin.org',
'User-Agent': 'Mozilla',
'X-Amzn-Trace-Id': 'Root=1-602f94a7-3aa49d8c48ea04345380c67b'},
'origin': '92.100.218.123',
'url': 'http://httpbin.org/get'}
如您所见,'User-Agent': 'Mozilla'
已发送。
我想知道如何在下面的get调用中传递header
headers = {
'User-Agent': 'Mozilla'
}
async def fetch(url, session):
async with session.get(url) as response:
resp = await response.read()
return resp
我尝试了以下但没有得到任何回应。
headers = {
'User-Agent': 'Mozilla'
}
async def fetch(url, session):
async with session.get(url, headers=headers) as response:
resp = await response.read()
return resp
objective是异步调用不同的url。需要知道是否还有其他替代方法,但无论如何,都需要通过 headers 才能获得正确的响应。
您可以对请求使用 httpbin.org 以查看服务器如何看待您的请求:
import asyncio
import aiohttp
from pprint import pprint
headers = {
'User-Agent': 'Mozilla'
}
async def fetch(url, session):
async with session.get(url, headers=headers) as response:
res = await response.json()
pprint(res)
async def main():
async with aiohttp.ClientSession() as session:
await fetch("http://httpbin.org/get", session)
asyncio.run(main())
结果:
{'args': {},
'headers': {'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Host': 'httpbin.org',
'User-Agent': 'Mozilla',
'X-Amzn-Trace-Id': 'Root=1-602f94a7-3aa49d8c48ea04345380c67b'},
'origin': '92.100.218.123',
'url': 'http://httpbin.org/get'}
如您所见,'User-Agent': 'Mozilla'
已发送。