python post请求抛出“ 400 Bad Request”

时间:2018-07-09 11:31:33

标签: python

我正在尝试执行以下脚本,在该脚本中尝试发送POST请求。我已经替换了标题部分中的一些值,以便将其发布到此处。我遇到的问题与从xmlFile.xml中读取的请求正文有关。文件与我的脚本位于同一目录中。 XML写在一行中,并从下一行开始:

<?xml version="1.0"?> 

能请你帮忙吗?我不明白为什么它会返回400 Bad Request。 XML可以单独正常运行,但不能在py脚本中运行。

#!/usr/bin/python
import httplib

def do_request(xmlFile):
    request = open(xmlFile, "r").read()
    conn = httplib.HTTPConnection("ipAddress", port)
    conn.putrequest("POST", "selector HTTP/1.1")
    conn.putheader("Content-Length", "%d" % len(request))
    conn.putheader("Content-Type", "text/xml")
    conn.putheader("Host", "ipAddress")
    conn.putheader("User-Agent", "userAgent")
    conn.endheaders()

    conn.send(request)

    response = conn.getresponse()
    print(response.status, response.reason)
    data = response.read()
    print(data)
    conn.close()

do_request('xmlFile.xml')

1 个答案:

答案 0 :(得分:1)

IIRC putrequest()的第二个参数应为网址的path部分(根为/)。 但是您正在使它变得比必须的复杂得多-您可以使用conn.request(method, path, params, headers) as showed here,或者(甚至更好)只使用python-requests(甚至官方的httplib文档也推荐它。)