POST请求适用于Postman,但不适用于Python [英] POST request works in Postman but not in Python

查看:729
本文介绍了POST请求适用于Postman,但不适用于Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在邮递员中发出此POST请求时,我得到了数据.当我在Python 2.7(使用Jupyter笔记本)中执行此操作时,出现错误无法解码JSON对象".我在做错什么,如何使它起作用?

When I make this POST request in Postman, I get the data. When I do it in Python 2.7 (using a Jupyter notebook), I get the error "No JSON object could be decoded". What am I doing wrong and how can I make it work?

import json
import requests
url = 'http://api.scb.se/OV0104/v1/doris/en/ssd/BE/BE0101/BE0101A/BefolkningNy'

headers={'content-type': 'application/json'}
payload = {  
"query": [
 {       
 "code": "ContentsCode",
  "selection": {        
    "filter": "item",         
    "values": [          
      "BE0101N1"         
    ]      
   }    
},    
{      
   "code": "Tid",
   "selection": {        
   "filter": "item",         
  "values": [           
   "2010",          
   "2011"         
   ]      
  }    
 },
 {      
  "code": "Region",
    "selection": {        
    "filter": "item",         
   "values": [           
   "01"         
   ]      
  }    
 }   
],  
"response": {    
  "format": "json"   
 }
}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}

r = requests.post(url, data=payload)
print(r.text)
print(r.json())

有关api的手册在这里,但并没有太大帮助:

The manual for the api is here, but it is not much help:

http: //www.scb.se/zh_/About-us/Open-data-API/API-for-the-Statistical-Database-/

推荐答案

设置json=payload,请求将添加您需要的标头:

Set json=payload and requests will add the headers you need:

url = 'http://api.scb.se/OV0104/v1/doris/en/ssd/BE/BE0101/BE0101A/BefolkningNy'
payload = ....


r = requests.post(url, json=payload)

这将为您提供json:

That will give you your json:

In [7]: 
   ...: r = requests.post(url, json=payload)
   ...: print(r.json())
   ...: 
{u'data': [{u'values': [u'2054343'], u'key': [u'01', u'2010']}, {u'values': [u'2091473'], u'key': [u'01', u'2011']}], u'comments': [], u'columns': [{u'text': u'region', u'code': u'Region', u'type': u'd'}, {u'text': u'year', u'code': u'Tid', u'type': u't'}, {u'text': u'Population', u'code': u'BE0101N1', u'type': u'c'}]}

如果碰巧遇到 json.decoder.JSONDecodeError:意外的UTF-8 BOM(使用utf-8-sig解码):错误将编码设置为 utf-8-sig :

If you happen to get an json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): error set the encoding to utf-8-sig:

r = requests.post(url, json=payload)
r.encoding = "utf-8-sig"
print(r.json())

这篇关于POST请求适用于Postman,但不适用于Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆