python requests get方式怎么设置请求头?

Python011

python requests get方式怎么设置请求头?,第1张

Header可以通过Request提供的.add_header()方法进行添加,示例代码如下:

123456789101112# -*- coding:utf-8 -*-

import urllib2import urlliburl = 'http://ah.example.com'half_url = u'/servlet/av/jd?

ai=782&ji=2624743&sn=I'#构造get请求req = urllib2.

Request(url+half_url.

encode('utf-8'))#添加headerreq.add_header('AcceptEncoding', 'gzip,deflate')req.

add_header('User-Agent','Mozilla/5.0')response = urllib2.

urlopen(req)

print response.

Requests支持流式上传,这允许你发送大的数据流或文件而无需先把它们读入内存。要使用流式上传,仅需为你的请求体提供一个类文件对象即可。

读取文件请使用字节的方式,这样Requests会生成正确的Content-Length。

with open('massive-body', 'rb') as f:

requests.post('http://some.url/streamed', data=f)

分块传输编码

对于出去和进来的请求,Requests也支持分块传输编码。要发送一个块编码的请求,仅需为你的请求体提供一个生成器

注意生成器输出应该为bytes

def gen():

yield b'hi'

yield b'there'

requests.post('http://some.url/chunked', data=gen())

For chunked encoded responses, it's best to iterate over the data

using Response.iter_content(). In an ideal situation you'll have set stream=True on the

request, in which case you can iterate chunk-by-chunk by calling iter_content with a chunk

size parameter of None. If you want to set a maximum size of the chunk, you can set a chunk

size parameter to any integer.

Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。

get()方法语法:

返回指定键的值,如果值不在字典中返回默认值None。

以下实例展示了 get()函数的使用方法:

以上实例输出结果为: