如何调试使用基本身份验证处理程序的urllib2请求 [英] How to debug urllib2 request that uses a basic authentication handler
本文介绍了如何调试使用基本身份验证处理程序的urllib2请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 urllib2
和 HTTPBasicAuthHandler
提出请求:
I'm making a request using urllib2
and the HTTPBasicAuthHandler
like so:
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状态代码?
I'm currently getting a httplib.BadStatusLine
exception when running this code. How could I go about debugging? Is there a way to see what the raw response is regardless of the unrecognized HTTP status code?
推荐答案
你尝试设置调试级别在您自己的HTTP处理程序中?将您的代码更改为这样:
Have you tried setting the debug level in your own HTTP handler? Change your code to something like this:
>>> 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发送/回复周期。
That will show the raw HTTP send / reply cycle on stderr.
从评论编辑
这是否有效?
... same code as above this line
opener=urllib2.build_opener(authhandler, urllib2.HTTPHandler(debuglevel=1))
... rest of your code
这篇关于如何调试使用基本身份验证处理程序的urllib2请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文