Python 2.7 HTTP基本身份验证

2024-05-13 02:20:27 发布

您现在位置:Python中文网/ 问答频道 /正文

也许有人能帮我。我正在尝试使用Python2.7和HTTP基本身份验证从网站获取数据。 该网站提供的唯一说明如下:

In order for your web service client to authenticate using basic authentication, the first HTTPS request must include the "Authorization" header specifying the account credentials to authenticate with. The header for a such a request would look like this:

  GET /polcs/trade.xml HTTP/1.0
  Host: secure.pol.com
  Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

我尝试了几件事,但都不管用,例如:

import urllib2
import base64

b = base64.encodestring('USERNAME:PASSWORD').replace('\n', '')
conf = {'headers': {'GET': '/polcs/trade.xml HTTP/1.0', 'Authorization': 'Basic ' + b},
    'url': 'secure.pol.com'}
datas = None
request = urllib2.Request(conf['url'], datas, conf['headers'])
result = urllib2.urlopen(request)

这一个给了我HTTP错误403:

url = 'https://secure.pol.com/polcs/data.xml'
request = urllib2.Request(url)
b = base64.encodestring('USERNAME:PASSWORD').replace('\n', '')
request.add_header("Authorization", "Basic " + b)
result = urllib2.urlopen(request)

有人能告诉我,我在哪里获取数据会出错吗? 谢谢大家!


Tags: thecomhttpurlbasicrequestconfxml