How to fix httplib.BadStatusLine exception?

試著忘記壹切 提交于 2019-12-17 16:40:14

问题


URL = "MY HTTP REQUEST URL"
XML = "<port>0</port>"

parameter = urllib.urlencode({'XML': XML})
response = urllib.urlopen(URL, parameter)
print response.read()


IOError: ('http protocol error', 0, 'got a bad status line', None)

I am trying to send XML to a server and get back XML. Is there any way to fix / ignore this exception?

I know that the status line is empty which is raising this error.


回答1:


Try to have a look what your server actually returns! It probably isn't a valid HTTP response. You could use something like this to send a raw http request to the server:

from socket import socket

host = 'localhost'
port = 80
path = "/your/url"
xmlmessage = "<port>0</port>"

s = socket()
s.connect((host, port))
s.send("POST %s HTTP/1.1\r\n" % path)
s.send("Host: %s\r\n" % host)
s.send("Content-Type: text/xml\r\n")
s.send("Content-Length: %d\r\n\r\n" % len(xmlmessage))
s.send(xmlmessage)
for line in s.makefile():
    print line,
s.close()

The response should look something like:

HTTP/1.1 200 OK
<response headers>

<response body>


来源:https://stackoverflow.com/questions/10708828/how-to-fix-httplib-badstatusline-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!