通过Python请求模块发出HTTP请求不能通过curl的代理工作吗?为什么?

dal*_*ler 11 python proxy get http-request python-requests

使用此curl命令,我能够从Bash中获取我正在寻找的响应

curl -v -u z:secret_key --proxy http://proxy.net:80  \
-H "Content-Type: application/json" https://service.com/data.json
Run Code Online (Sandbox Code Playgroud)

我已经在使用Requests模块的代理上看到过这篇文章

它帮助我在Python中制定我的代码,但我需要通过代理提出请求.但是,即使在提供适当的代理时,它也无法正常工作.也许我只是没有看到什么?

>>> requests.request('GET', 'https://service.com/data.json', \
>>> headers={'Content-Type':'application/json'}, \ 
>>> proxies = {'http' : "http://proxy.net:80",'https':'http://proxy.net:80'}, \
>>> auth=('z', 'secret_key'))
Run Code Online (Sandbox Code Playgroud)

此外,在同一个python控制台上,我可以使用urllib发出请求,使其成功.

>>> import urllib
>>> urllib.urlopen("http://www.httpbin.org").read()
---results---
Run Code Online (Sandbox Code Playgroud)

即使只在非https地址上尝试请求也无法正常工作.

>>> requests.get('http://www.httpbin.org')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.6/site-packages/requests/api.py", line 79, in get
   return request('get', url, **kwargs)
File "/Library/Python/2.6/site-packages/requests/api.py", line 66, in request
    prefetch=prefetch
File "/Library/Python/2.6/site-packages/requests/sessions.py", line 191, in request
    r.send(prefetch=prefetch)
File "/Library/Python/2.6/site-packages/requests/models.py", line 454, in send
    raise ConnectionError(e)
requests.exceptions.ConnectionError: Max retries exceeded for url:
Run Code Online (Sandbox Code Playgroud)

请求是如此优雅和令人敬畏,但在这种情况下怎么会失败?

rav*_*c95 9

问题实际上在于python的标准url访问库 - urllib/urllib2/httplib.我不记得哪个库是确切的罪魁祸首,但为了简单起见,我们只需将其称为urllib.遗憾的是,urllib没有实现通过http(s)代理访问https站点所需的HTTP Connect方法.我使用urllib添加功能的努力没有成功(自从我尝试以来已经有一段时间了).所以不幸的是,我知道工作的唯一选择是在这种情况下使用pycurl.

但是,有一个相对干净的解决方案几乎与python请求完全相同的API,但它使用pycurl后端而不是python标准库.

该库名为human_curl.我自己用过它并取得了很好的效果.