【问题标题】:Using curl to POST obtains a different response than when using requests to POST使用 curl POST 获得的响应与使用请求 POST 不同
【发布时间】:2015-06-10 17:14:40
【问题描述】:

我是 python 编程的新手,我遇到了一个似乎无法解决的僵局。我正在尝试使用 python requests 模块向 IBM Bluemix 中的服务发布请求。当我使用 cURL 发出请求时它工作正常,但是当我尝试请求模块时,我收到一条错误消息。由于我使用的是相同的数据文件,我对为什么得到不同的结果感到困惑。谁能赐教?

这是修改了访问密钥和 URL 的代码,以及我认为响应的相关部分: 这是卷曲:

curl -i -v -H "Content-type: application/json" -X POST \
  "https://ibm.Someservice.ibmcloud.com:9999/Action/modelName?accesskey=XXXXYYYYYZZZZZ+++++etc"  \
  --data-binary @sample-data.json

这里是请求代码:

import requests
import json

def post2ndRequest():
    url = 'https://ibm.Someservice.ibmcloud.com:9999/Action/modelName?accesskey=XXXXYYYYYZZZZZ+++++etc'
    files = {'file': open('sample-data.json', 'rb')}
    headers = {'Content-Type':'application/json'}
    r = requests.post(url, headers=headers, files=files)
    print(r.text)
    return r.text

temp = 'PMresponseX.txt'
F = open (temp,'wb')
F.write(post2ndRequest())  
F.close()

这里是返回响应的一部分:

<body><h1>HTTP Status 500 - org.codehaus.jackson.JsonParseException:
Unexpected character ('-' (code 45)) in numeric value: expected digit
(0-9) to follow minus sign, for valid numeric value</h1><HR size="1"
noshade="noshade"><p><b>type</b> Exception report</p><p><b>message</b>
<u>org.codehaus.jackson.JsonParseException: Unexpected character ('-'
(code 45)) in numeric value: expected digit (0-9) to follow minus
sign, for valid numeric value</u></p><b>description</b> <u>The server
encountered an internal error that prevented it from fulfilling this
request.</u></p>

这似乎是服务器中的某种解析错误,但 cURL 工作正常,所以服务器端似乎没问题,...我之前成功使用过请求模块,但没有使用 https,也没有将访问密钥附加到 URL .这可能是问题吗?任何帮助将不胜感激!

【问题讨论】:

  • 两个请求的完整 HTTP 转储会有所帮助。使用 Wireshark 之类的工具记录转储,然后比较不同之处。

标签: python curl


【解决方案1】:

您正在使用curl--data-binary 选项,根据手册页:

This  posts data exactly as specified with no extra pro‐ cessing
whatsoever.

而在您对requests.post 的调用中,您使用的是files 参数,根据文档:

:param files: (optional) Dictionary of ``'name': file-like-objects``
 (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload.

您似乎真的想使用data 参数:

:param data: (optional) Dictionary, bytes, or file-like object
to send in the body of the :class:`Request`.

您当前的代码正在发送一个多部分的 MIME 存档,其中服务器期待完全不同的内容。

【讨论】:

  • 感谢拉斯克斯。我将文件读入一个变量,该变量作为数据传递给请求,果然,它起作用了。我以为我已经尝试过了,但我一定是把它与另一个项目混淆了。那太好了。问题解决了。再次感谢。
猜你喜欢
  • 2019-10-11
  • 2012-09-13
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-28
  • 1970-01-01
相关资源
最近更新 更多