urllib2.urlopen(request) -- BadStatusLine的错误

2 views
Skip to first unread message

吴道远

unread,
May 29, 2010, 1:58:56 AM5/29/10
to cisrg...@googlegroups.com, pyth...@googlegroups.com, nup...@googlegroups.com
我做的HTTP Proxy的代码里的这句话老是异常:
line 70: response = urllib2.urlopen(request)

基本思路是,
从用户请求中提取他想访问的网址:
line 58: url = self.path
然后,我们的proxy自己来创建这个请求:
line 66: #request = urllib2.Request(url)
从远端服务器拿到response后再转发给本地浏览器。

现在,为了测试,把line 66替换成line 65,即用户输入任何网址,访问到的都是百度。
line 65: request = urllib2.Request('http://www.baidu.com')

测试时需要手动把浏览器的代理改成:127.0.0.1,端口:8013
我之前测试成功的,在4.28号时。但昨天再次开始写的时候,发现怎么测试都不ok。折腾了昨天一天,实在不行,决定问问group里的朋友有没有遇到过。

我自己google的时候,症状和问题都跟下面的两个链接很类似,我在Python2.5版和Python2.6版里测试都不成功。它的链接也没给出明确的解决思路,它的问题是https不能,http可以。

完整的异常信息在附件:Exception_BadStatusLine.txt
话说我还是不会很好地用这个异常信息,跟着它走一遍也没太多思路,在看httplib.py……
完整的代码在附件:HttpProxy.py
Exception_BadStatusLine.txt
HttpProxy.py

吴道远

unread,
May 29, 2010, 4:45:05 AM5/29/10
to cisrg...@googlegroups.com, pyth...@googlegroups.com, nup...@googlegroups.com
我下面这段测试程序就一点问题都没有,能正常返回网页信息:
import urllib2
import os

request = urllib2.Request('http://www.baidu.com')

try:
    response = urllib2.urlopen(request)
except urllib2.HTTPError, errMsg:
    errNum = int( str(errMsg).split(' ')[2].split(':')[0] )
    print(errNum)
    os._exit(0)

print( response.read() )
os.system('pause')

然后,我不设置浏览器的代理,而直接访问http://127.0.0.1:8013/,是可以的。能正常显示百度的页面。

我在想,是不是一定要用urllib2.ProxyHandler来替换掉默认的opener:
opener = urllib2.build_opener(proxy_handler)
试试。。。可能默认的opener只支持纯粹的服务器的双方,而不支持代理服务器的三方交互,proxy跟远程web服务器的连接被提前终止了?

在httplib.py中的出错代码段能反映出啥信息?
line = self.fp.readline()
if not line:
# Presumably, the server closed the connection before
# sending a valid response.
raise BadStatusLine(line)


2010/5/29 吴道远 <clz...@gmail.com>

吴道远

unread,
May 29, 2010, 5:16:22 AM5/29/10
to cisrg...@googlegroups.com, pyth...@googlegroups.com, nup...@googlegroups.com
OMG, 终于搞定了。。。

这种情况下,我们用urllib2来访问远端服务器时是不需要代理的,而默认的urlopen使用了ProxyHandler:(把这个取消掉就ok了)

In addition, default installed ProxyHandler makes sure the requests are handled through the proxy when they are set.

刚刚思路有点混乱,这种说法是完成不正确的:是不是一定要用urllib2.ProxyHandler来替换掉默认的opener。

本来urllib2.urlopen()就希望能跳过本地的代理设置,直接访问远端服务器。因为目前本地的代理设置只是为了重定向浏览器的请求到本地的proxy。

2010/5/29 吴道远 <clz...@gmail.com>
Reply all
Reply to author
Forward
0 new messages