python - 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')
解决方案
IIRC 的第二个参数putrequest()
应该是path
url 的一部分(/
用于根)。但是你让它变得比它必须的复杂得多 - 你可以使用conn.request(method, path, params, headers)
这里显示的,或者(甚至更好)只是python-requests
实际使用(甚至官方的 httplib 文档也推荐它)。
推荐阅读
- pointers - 没有返回关键字的对象返回
- powershell - 如何将 prnmngr 的输出转换为自定义对象?
- google-cloud-platform - 在 Google Cloud Composer 中运行气流 cli
- vb.net - 无法在 VB 中为 ______ 创建清单资源名称
- javascript - IBM API Connect:编码和解码 URL
- sbt - 如何让 Akka Java 测试在 sbt 中运行
- javascript - 收藏品未出现在画布中
- linux - 虚拟地址何时分配给程序/进程?
- javascript - jquery 在我的浏览器上不起作用认为相同的代码适用于 jsfiddle 尝试了所有必要的标签以及 noconflict 标签
- css - 为什么我的布局不起作用?