使用curl进行POST会获得与使用POST请求时不同的响应

时间:2015-06-10 17:14:41

标签: python curl

我是python编程的新手,我已经陷入了一个似乎无法解决的僵局。我正在尝试使用python请求模块将请求POST到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,也没有将访问密钥附加到URL 。这可能是问题吗?任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

您正在使用--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存档,其中服务器期望完全不同的东西。