urllib2 http请求通过代理进行身份验证

时间:2016-12-18 01:28:30

标签: python

我理解通过身份验证从http获取资源的最常用方法是使用以下代码。

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n',   '')
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

我的问题是,如果我需要设置代理,我应该在上面的代码块中添加什么代码?我尝试了下面的那个,但它没有用。错误消息是urllib2.URLError:

<urlopen error [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>

以下是代码:

import urllib2
import base64


proxy_id = "ididid"
proxy_pw = "password"
proxyhandler = urllib2.ProxyHandler({"http":"http://"+proxy_id+":"+proxy_pw+"@proxy:8080"})
opener = urllib2.build_opener(proxyhandler)
urllib2.install_opener(opener)


request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n',   '')
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)  

2 个答案:

答案 0 :(得分:0)

如果您的代理服务器要求您使用用户/通过身份验证,则应使用ProxyBasicAuthHandler

import urllib2
import base64


proxy_id = "ididid"
proxy_pw = "password"

proxy_handler = urllib2.ProxyHandler({'http': 'http://proxy:8080'})
proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', proxy_id, proxy_pw)

opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)
urllib2.install_opener(opener)

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n',   '')
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)  

答案 1 :(得分:0)

对不起这个问题。代码完全正确。我使用了错误的代理http,因此造成了所有问题。