python post 请求与 curl 工具比较

python post request compare to curl tool

在我的项目中

我用过

curl -I url -H"Content-Type: application/octet-stream" -X POST

一切正常。

但是在python中我使用了请求模块

response = requests.post(url, data="mystring", headers="Content-Type: application/octet-stream")

然后我得到了400错误,意思是:Bad request;请求格式不正确,无法处理。

可能是什么问题?

您确定 url 和数据对于 curl 和请求完全相同吗?

尝试一些基本的故障排除。假设 url 和数据字符串是正确的。您确定可以访问服务器吗? curl 请求是一个终端命令,连接方式不同于 python API 类型的命令,python 可能需要您的服务器打开额外的权限。如果你是 运行 Apache,你需要确保它允许 scirpted headers

读这个: http://httpd.apache.org/docs/2.2/mod/mod_headers.htmlhttp://httpd.apache.org/docs/2.2/mod/mod_headers.html

也尝试使用其他库连接的替代方法,就像这个线程上的人所做的那样:

" 使用 httplib

import httplib
conn = httplib.HTTPConnection("www.google.com")
conn.request("HEAD", "/index.html")
res = conn.getresponse()
print res.status, res.reason
200 OK
print res.getheaders()
[('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]