首页 > 解决方案 > python post请求抛出'400 Bad Request'

问题描述

我正在尝试执行下面的脚本,我尝试发送 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')

标签: python

解决方案


IIRC 的第二个参数putrequest()应该是pathurl 的一部分(/用于根)。但是你让它变得比它必须的复杂得多 - 你可以使用conn.request(method, path, params, headers) 这里显示的,或者(甚至更好)只是python-requests实际使用(甚至官方的 httplib 文档也推荐它)。


推荐阅读