如何用Python发出POST请求?

2024-06-29 00:02:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用Python发出POST请求 这是我的发帖请求:

POST http://services.data.shom.fr/sos/client
Content-Type: application/json
{
  "request": "GetObservation",
  "service": "SOS",
  "version": "2.0.0",
  "procedure": [
    "http://shom.fr/maregraphie/procedure/3"
  ],
  "offering": [
    "http://shom.fr/maregraphie/offering/3"
  ],
  "observedProperty": [
    "http://shom.fr/maregraphie/observedProperty/WaterHeight/4"
  ],
  "featureOfInterest": [
    "http://shom.fr/maregraphie/featureOfInterest/5"
  ],
  "temporalFilter": [
    {
      "during": {
        "ref": "om:phenomenonTime",
        "value": [
          "2014-01-01T00:00:00Z",
          "2014-12-31T00:00:00Z"
        ]
      }
    }
  ]
}

下面是我的Python脚本:

^{pr2}$

我得到了一个语法错误,我知道我的有效载荷变量的语法是不正确的,但我不能找出它。有什么想法吗?在


Tags: clienthttpdataservicecontentfrpostprocedure
1条回答
网友
1楼 · 发布于 2024-06-29 00:02:44

多谢了,真管用! 下面是python的最终代码:

#!/usr/bin/python3.4

import requests
import json

# Server URL's
url = 'http://services.data.shom.fr/sos/client'
#
payload = {
    'request': 'GetObservation',
    'service': 'SOS',
    'version': '2.0.0',
    'procedure': ['http://shom.fr/maregraphie/procedure/3'],
    'offering': ['http://shom.fr/maregraphie/offering/3'],
    'observedProperty': ['http://shom.fr/maregraphie/observedProperty/WaterHeight/4'],
    'featureOfInterest': ['http://shom.fr/maregraphie/featureOfInterest/5'],
    'temporalFilter': [{'during': {'ref': 'om:phenomenonTime','value': ['2014-01-01T00:00:00Z','2014-12-31T00:00:00Z']}}]
}
#Header for the POST request
headers = {'Content-Type': 'application/json'}

#Request
r = requests.post(url,data = json.dumps(payload), headers=headers)
#Write response in a text file
f = open('text.txt', 'w')
f.write(r.text)
f.close()

相关问题 更多 >