解决python2-request自动编码、参数顺序问题

自动编码问题

有时候我们希望发出如下数据包:

1
2
3
4
5
6
GET /?c=<?=phpinfo();?> HTTP/1.1
Host: 127.0.0.1
Connection: close
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.22.0

通常程序会这么写:

1
2
3
import requests
url = 'http://127.0.0.1/?c=<?=phpinfo();?>'
resp = requests.get(url=url, verify=False)

但是使用这种写法,python会将URL中的特殊字符自动编码,例如上面代码发出的数据包实际如下:

1
2
3
4
5
6
GET /?c=%3C?=phpinfo();?%3E HTTP/1.1
Host: 127.0.0.1
Connection: close
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.22.0

想解决自动编码问题,可使用如下代码:

1
2
3
4
5
6
7
8
9
10
11
import requests
from urllib import unquote

class NoQuotedCommasSession(requests.Session):
def send(self, *a, **kw):
a[0].url = unquote(a[0].url) # a[0] is prepared request
return requests.Session.send(self, *a, **kw)

url = 'http://127.0.0.1/?c=<?=phpinfo();?>'
s = NoQuotedCommasSession()
s.get(url=url, verify=False)

参数顺序问题

有时候我们希望发出如下数据包:

1
2
3
4
5
6
7
8
9
10
POST / HTTP/1.1
Host: 127.0.0.1
Connection: close
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.22.0
Content-Length: 38
Content-Type: application/x-www-form-urlencoded

param1=fool1&param2=fool2&param3=fool3

且参数顺序必须和上面一致时,我们就可以传一个有序字典给request的data参数,具体代码如下:

1
2
3
4
5
6
7
8
9
10
import requests
import collections

url = 'http://127.0.0.1'
data = collections.OrderedDict()
data['param1'] = 'fool1'
data['param2'] = 'fool2'
data['param3'] = 'fool3'

resp = requests.post(url=url, data=data, verify=False)
文章作者: Mochazz
文章链接: https://mochazz.github.io/2020/02/27/解决python2-request自动编码、参数顺序问题/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Mochazz's blog