如何在Python中发出POST请求?

时间:2015-06-20 23:17:18

标签: python python-requests

我正在尝试使用Python发出POST请求 这是我的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脚本:

#!/usr/bin/python3.4

import requests
import json


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'
        ]
      }
    }
  ]
}
headers = {'Content-Type': 'application/json'}
r = requests.post(url,data = payload, headers=headers)
f = open('text.txt', 'w')
f.write(r.text)
f.close()

我收到语法错误,我明白我的有效负载变量的语法不正确,但我无法理解。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

非常感谢,它有效! 这是最后的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()
相关问题