pythonrestful接口返回json utf8_如何使用Python从RESTful服务获取JSON数据?

如何使用Python从RESTful服务获取JSON数据?

有没有使用Python从RESTful服务获取JSON数据的标准方法?

我需要使用kerberos进行身份验证。

一些片段会有所帮助。

5个解决方案

111 votes

我会试试请求库。 基本上只是一个更容易使用的标准库模块(即urllib2,httplib2等)的包装器,你可以使用相同的东西。 例如,从需要基本身份验证的URL获取json数据将如下所示:

import requests

response = requests.get('http://thedataishere.com',

auth=('user', 'password'))

data = response.json()

对于kerberos身份验证,请求项目具有reqests-kerberos库,该库提供可用于请求的kerberos身份验证类:

import requests

from requests_kerberos import HTTPKerberosAuth

response = requests.get('http://thedataishere.com',

auth=HTTPKerberosAuth())

data = response.json()

Mark Gemmill answered 2019-04-21T01:13:30Z

75 votes

除非我忽略了这一点,否则这样的事情应该有效:

import json

import urllib2

json.load(urllib2.urlopen("url"))

Trufa answered 2019-04-21T01:12:58Z

25 votes

您基本上需要向服务发出HTTP请求,然后解析响应的主体。 我喜欢使用httplib2:

import httplib2 as http

import json

try:

from urlparse import urlparse

except ImportError:

from urllib.parse import urlparse

headers = {

'Accept': 'application/json',

'Content-Type': 'application/json; charset=UTF-8'

}

uri = 'http://yourservice.com'

path = '/path/to/resource/'

target = urlparse(uri+path)

method = 'GET'

body = ''

h = http.Http()

# If you need authentication some example:

if auth:

h.add_credentials(auth.user, auth.password)

response, content = h.request(

target.geturl(),

method,

body,

headers)

# assume that content is a json reply

# parse content with the json module

data = json.loads(content)

Christo Buschek answered 2019-04-21T01:13:54Z

7 votes

如果您希望使用Python 3,可以使用以下内容:

import json

import urllib.request

req = urllib.request.Request('url')

with urllib.request.urlopen(req) as response:

result = json.loads(response.readall().decode('utf-8'))

Andre Wisplinghoff answered 2019-04-21T01:14:19Z

3 votes

首先,我认为为此您推出自己的解决方案就是urllib2或httplib2。 无论如何,如果您确实需要通用REST客户端,请检查这一点。

[https://github.com/scastillo/siesta]

但是我认为库的功能集对大多数Web服务都不起作用,因为它们可能会使用oauth等。 此外,我不喜欢它写在httplib上的事实,这是一个痛苦,与httplib2相比,如果你不需要处理大量的重定向等仍然适用于你。

dusual answered 2019-04-21T01:14:57Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值