python:httplib错误:无法发送标头 [英] python: httplib error: can not send headers

查看:177
本文介绍了python:httplib错误:无法发送标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

conn = httplib.HTTPConnection('thesite')
conn.request("GET","myurl")
conn.putheader('Connection','Keep-Alive')
#conn.putheader('User-Agent','Mozilla/5.0(Windows; u; windows NT 6.1;en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome//5.0.375.126 Safari//5.33.4')
#conn.putheader('Accept-Encoding','gzip,deflate,sdch')
#conn.putheader('Accept-Language','en-US,en;q=0.8')
#conn.putheader('Accept-Charset','ISO-8859-1,utf-8;1=0.7,*;q=0.3')
conn.endheaders()
r1= conn.getresponse()

它引发了错误:

  conn.putheader('Connection','Keep-Alive')
  File "D:\Program Files\python\lib\httplib.py", line 891, in putheader
    raise CannotSendHeader()

如果我注释掉 putheader endheaders ,它运行正常。但我需要保持活力。

If I comment out putheader and endheaders, it runs fine. But I need it to be keep alive.

有谁知道我做错了什么?

Does anyone know what I did wrong?

推荐答案

使用 putrequest 而不是 request 。由于 request 也可以发送标题,它会向服务器发送一个空行以指示标题的结尾,因此之后发送标题会产生错误。

Use putrequest instead of request. Since request also can send headers, it will send a blank line to the server to indicate end of headers, so sending headers afterward will create an error.

或者,你可以像这里那样做:

Alternatively, you could do as is done here:

import httplib, urllib
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn = httplib.HTTPConnection("musi-cal.mojam.com:80")
conn.request("POST", "/cgi-bin/query", params, headers)
response = conn.getresponse()

这篇关于python:httplib错误:无法发送标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆