2014-06-05 94 views
3

我對Python很新穎,我一直在使用他們的請求模塊來替代PHP的cURL庫。我的代碼如下HTTPS代理不能與Python的請求模塊一起工作

import requests 
import json 
import os 
import urllib 
import math 
import sys 

def main() :  
    url = 'https://api.com' 

    headers = {'Content-Type': 'application/json; charset=utf-8', 
       'User-Agent': '(iPhone; iOS 7.0.4; Scale/2.00)'} 

    d = {'token': "12345"} 

    proxies = { 
     "https": "https://27.254.52.99:8080", 
    } 

    post = json.dumps(d); 
    r = requests.post(url, data=post, headers=headers, proxies=proxies) 
    print r.json 

if __name__ == "__main__": 
    main() 

不過,我招呼着以下錯誤:

File "test.py", line 42, in test 
r = requests.post(url, data=post, headers=headers, proxies=proxies) 
File "/Library/Python/2.7/site-packages/requests-2.2.1-py2.7.egg/requests/api.py", line 88, in post 
return request('post', url, data=data, **kwargs) 
File "/Library/Python/2.7/site-packages/requests-2.2.1-py2.7.egg/requests/api.py", line 44, in request 
return session.request(method=method, url=url, **kwargs) 
File "/Library/Python/2.7/site-packages/requests-2.2.1-py2.7.egg/requests/sessions.py", line 383, in request 
resp = self.send(prep, **send_kwargs) 
File "/Library/Python/2.7/site-packages/requests-2.2.1-py2.7.egg/requests/sessions.py", line 486, in send 
r = adapter.send(request, **kwargs) 
File "/Library/Python/2.7/site-packages/requests-2.2.1-py2.7.egg/requests/adapters.py", line 381, in send 
raise ProxyError(e) 
ProxyError: Cannot connect to proxy. Socket error: [Errno 54] Connection reset by peer. 
+0

找不到任何關於代碼的怪事。錯誤似乎表明存在連接問題。 curl或wget是否在同一臺機器上工作? –

+0

這裏也是一個很好的工具來玩代理。 http://www.charlesproxy.com/ –

回答

2

HTTPS被請求 '竊聽'。我不知道具體情況,但您可以在此網站上找到有關此問題的其他幾個主題。另外一個Github問題仍然有效here。我懷疑你遇到了那裏提到的問題。如果我完全錯了,有人糾正我。

驗證:

$~ curl --proxy https://27.254.52.99:8080 icanhazip.com 
27.254.52.99 

作品,但隨後在Python:

>>> proxies={'https': 'https://27.254.52.99:8080'} 
>>> r = requests.get('http://icanhazip.com', headers={'User-Agent': 'Bla'}, proxies=proxies) 
print r.content 
<my ipv6 address comes up> 

正如你看到的,我的地址出現,這意味着代理也沒做。

我不明白你爲什麼收到堆棧跟蹤。也許是因爲您的API也使用HTTPS(?)。或者,也許你的API只是...失望。

無論如何,如果代理服務器通過HTTP,代理服務器在請求中工作。

>>> proxies={'http': 'http://27.254.52.99:8080'} 
>>> r = requests.head('http://icanhazip.com', headers={'User-Agent': 'Bla'}, proxies=proxies) 
print r.content 
27.254.52.99 
+0

@ Lance:還有什麼好運氣? – cpb2

+0

對不起,他遲到了。是的,這對我有效。謝謝。 – Lance

+0

通過https://github.com/shazow/urllib3/pull/170添加https代理支持 –

相關問題