我对Python很陌生,我一直在使用他们的请求模块替代PHP的cURL库。我的代码如下
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 :(得分:4)
HTTPS在请求中被“窃听”。我不知道具体细节,但您可以在本网站上找到有关该问题的一些其他主题。此外,Github问题仍处于活动状态here。我怀疑你遇到了那里提到的问题。如果我完全错了,有人会纠正我。
验证:
$~ curl --proxy https://27.254.52.99:8080 icanhazip.com
27.254.52.99
Works,但后来在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
答案 1 :(得分:-1)
我使用tor作为代理解决了相同的问题。 可能是您的代理不起作用。 查看我的代码:
import requests
proxies = {
'http': 'socks5://localhost:9000',
'https': 'socks5://localhost:9000',
}
r = requests.Session()
r.proxies.update(proxies)
response = r.get('http://ifconfig.me/ip', proxies=proxies)
print(response.text)
我使用multitor作为代理!