簡體   English   中英

通過Python請求模塊發出HTTP請求不能通過curl的代理工作嗎?為什么?

[英]Making HTTP requests via Python Requests module not working via proxy where curl does? Why?

使用此curl命令,我能夠從Bash中獲取我正在尋找的響應

curl -v -u z:secret_key --proxy http://proxy.net:80  \
-H "Content-Type: application/json" https://service.com/data.json

我已經在使用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'))

此外,在同一個python控制台上,我可以使用urllib發出請求,使其成功。

>>> import urllib
>>> urllib.urlopen("http://www.httpbin.org").read()
---results---

即使只在非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:

請求是如此優雅和令人敬畏,但在這種情況下怎么會失敗?

問題實際上在於python的標准url訪問庫 - urllib / urllib2 / httplib。 我不記得哪個庫是確切的罪魁禍首,但為了簡單起見,我們只需將其稱為urllib。 遺憾的是,urllib沒有實現通過http(s)代理訪問https站點所需的HTTP Connect方法。 我使用urllib添加功能的努力沒有成功(自從我嘗試以來已經有一段時間了)。 所以不幸的是,我知道工作的唯一選擇是在這種情況下使用pycurl。

但是,有一個相對干凈的解決方案幾乎與python請求完全相同的API,但它使用pycurl后端而不是python標准庫。

該庫名為human_curl 我自己用過它並取得了很好的效果。

相信上面的答案,我們嘗試了human_curl

human_curl給出了諸如未知錯誤之類的錯誤,而urllib3給出了正確的錯誤,例如Request Timed out,Max retries超過了url。

所以,我們回到了urllib3,urllib3是線程安全的。 我們對urllib3感到滿意

現在只有問題我們得到它“超出最大重試次數”,我們無法解決它,猜測它可能與服務器/代理有關,但不確定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM