当我使用conn.getresponse()时,有一些错误

时间:2016-04-12 02:41:40

标签: python

import sys
import pdb
import http.client


def PassParse():


    headers = {"Accept":" application/json, text/plain, */*",
    "Authorization":" Basic YWRtaW46YXNkZg==",
    "Referer":" http://192.168.1.113:8080/#/apps",
    "Accept-Language":" zh-CN",
        "Accept-Encoding":" gzip, deflate",
    "User-Agent":" Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko LBBROWSER",
    "Host":" 192.168.1.113:8080",
    "DNT":" 1",
    "Connection":" Keep-Alive"};      
    conn = http.client.HTTPConnection("192.168.1.113:8080");     

    conn.request(method="Get",url="/api/v1/login",body=None,headers=headers);     

    response = conn.getresponse();
    responseText = response.getheaders("content-lentgh");
    print ("succ!^_^!");
    #print (response.status);
    print (responseText);  
    conn.close();  


run error:
Traceback (most recent call last):
  File "F:\Python\test1-3.4.py", line 32, in <module>
    PassParse();
  File "F:\Python\test1-3.4.py", line 24, in PassParse
    response = conn.getresponse();
  File "E:\program files\Python 3.4.3\lib\http\client.py", line 1171, in getresponse
    response.begin()
  File "E:\program files\Python 3.4.3\lib\http\client.py", line 351, in begin
    version, status, reason = self._read_status()
  File "E:\program files\Python 3.4.3\lib\http\client.py", line 333, in _read_status
    raise BadStatusLine(line)
http.client.BadStatusLine: <html>

3 个答案:

答案 0 :(得分:0)

来自httplib的Python文档:

exception httplib.BadStatusLine
A subclass of HTTPException. Raised if a server responds with a HTTP status code that we don’t understand.

听起来你的API可能没有返回可以被解析为具有有效HTTP状态代码的有效HTTP响应的东西。您可能希望检查API端点的代码是否按预期工作并且没有失败。

除此之外,你的代码运行正常,除了一件事:response.getheader()接受一个参数,而response.getheaders()不接受任何参数,所以一旦解决了BadStatusLine异常,Python就会抱怨

答案 1 :(得分:0)

似乎httpserver没有返回有效的http响应,你可以使用telnet来检查它。

telnet 192.168.1.113 8080

然后发送:

GET /api/v1/login HTTP/1.1

参考:https://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html

答案 2 :(得分:0)

我使用以下代码解决了问题:

来自requests.auth的

导入HTTPBasicAuth

res = requests.get('http://192.168.1.113:8080/api/v1/login',auth =(用户名,密码));