我正在尝试使用Python请求重现以下curl命令:
curl -X POST -H 'Content-Type: application/gpx+xml' -H 'Accept: application/json' --data-binary @test.gpx "http://test.roadmatching.com/rest/mapmatch/?app_id=my_id&app_key=my_key" -o output.json
卷曲的请求工作正常。现在,我用Python尝试一下:
import requests
file = {'test.gpx': open('test.gpx', 'rb')}
payload = {'app_id': 'my_id', 'app_key': 'my_key'}
headers = {'Content-Type':'application/gpx+xml', 'Accept':'application/json'}
r = requests.post("https://test.roadmatching.com/rest/mapmatch/", files=file, headers=headers, params=payload)
我得到了错误:
<Response [400]>
{u'messages': [], u'error': u'Invalid GPX format'}
我究竟做错了什么?我必须指定一个data-binary
地方吗?
此处记录了该API:https://mapmatching.3scale.net/mmswag
Curl将文件上传为POST主体本身,但是您要求requests
将其编码为multipart / form-data主体。不要files
在这里使用,将文件对象作为data
参数传递:
import requests
file = open('test.gpx', 'rb')
payload = {'app_id': 'my_id', 'app_key': 'my_key'}
headers = {'Content-Type':'application/gpx+xml', 'Accept':'application/json'}
r = requests.post(
"https://test.roadmatching.com/rest/mapmatch/",
data=file, headers=headers, params=payload)
如果您在with
声明中使用该文件,则上传后将为您关闭:
payload = {'app_id': 'my_id', 'app_key': 'my_key'}
headers = {'Content-Type':'application/gpx+xml', 'Accept':'application/json'}
with open('test.gpx', 'rb') as file:
r = requests.post(
"https://test.roadmatching.com/rest/mapmatch/",
data=file, headers=headers, params=payload)
(HTTP)这将完全按照指定的方式发布数据,而不会进行任何额外处理。
如果您以字母开头的数据
@
,其余的应该是文件名。数据以与发布类似的方式发布--data-ascii
,除了保留换行符和回车符,并且永远不会进行转换。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句