我是 python 编程的新手,我遇到了似乎无法解决的僵局。我正在尝试使用 python 请求模块将请求发布到 IBM Bluemix 中的服务。当我使用 cURL 发出请求时它工作正常但是当我尝试请求模块时我收到一条错误消息。由于我使用的是相同的数据文件,所以我很困惑为什么会得到不同的结果。谁能赐教一下?
这是修改了访问键和 URL 的代码以及我认为是响应的相关部分: 这是 curl :
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,也没有将访问 key 附加到 URL .这可能是问题所在吗?任何帮助将不胜感激!
请您参考如下方法:
您正在使用 --data-binary 选项来 curl,根据手册页:
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 存档,其中服务器期待完全不同的东西。
