如何调试使用基本身份验证手的urllib2请求

2024-05-15 22:47:36 发布

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

我正在使用urllib2HTTPBasicAuthHandler发出请求,如下所示:

import urllib2

theurl = 'http://someurl.com'
username = 'username'
password = 'password'

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, theurl, username, password)

authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)

params = "foo=bar"

response = urllib2.urlopen('http://someurl.com/somescript.cgi', params)

print response.info()

运行此代码时,我当前收到一个httplib.BadStatusLine异常。我怎么能开始调试呢?不管无法识别的HTTP状态代码如何,是否有方法查看原始响应是什么?


Tags: 代码comhttpresponseusernamepasswordparamsopener
1条回答
网友
1楼 · 发布于 2024-05-15 22:47:36

您是否尝试在自己的HTTP处理程序中设置调试级别?将代码更改为以下内容:

>>> import urllib2
>>> handler=urllib2.HTTPHandler(debuglevel=1)
>>> opener = urllib2.build_opener(handler)
>>> urllib2.install_opener(opener)
>>> resp=urllib2.urlopen('http://www.google.com').read()
send: 'GET / HTTP/1.1
      Accept-Encoding: identity
      Host: www.google.com
      Connection: close
      User-Agent: Python-urllib/2.7'
reply: 'HTTP/1.1 200 OK'
header: Date: Sat, 08 Oct 2011 17:25:52 GMT
header: Expires: -1
header: Cache-Control: private, max-age=0
header: Content-Type: text/html; charset=ISO-8859-1
... the remainder of the send / reply other than the data itself 

因此,要准备的三行是:

handler=urllib2.HTTPHandler(debuglevel=1)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
... the rest of your urllib2 code...

这将在stderr上显示原始HTTP发送/回复周期。

从评论编辑

这有用吗?

... same code as above this line
opener=urllib2.build_opener(authhandler, urllib2.HTTPHandler(debuglevel=1))
... rest of your code

相关问题 更多 >