使用Python发送JSON请求 [英] Sending JSON request with Python

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

问题描述

我是Web服务的新手,正在尝试使用python脚本发送以下基于JSON的请求:

I'm new to web services and am trying to send the following JSON based request using a python script:

http://myserver/emoncms2/api/post?apikey=xxxxxxxxxxxxx&json={power:290.4,temperature:19.4}

如果将以上内容粘贴到浏览器中,它将按预期工作.但是,我正在努力从Python发送请求.以下是我正在尝试的:

If I paste the above into a browser, it works as expected. However, I am struggling to send the request from Python. The following is what I am trying:

import json
import urllib2
data = {'temperature':'24.3'}
data_json = json.dumps(data)
host = "http://myserver/emoncms2/api/post"
req = urllib2.Request(host, 'GET', data_json, {'content-type': 'application/json'})
response_stream = urllib2.urlopen(req)
json_response = response_stream.read()

如何将apikey数据添加到请求中?

How do I add the apikey data into the request?

谢谢!

推荐答案

您可以使用请求,而不是使用urllib2 .这个新的python库确实写得很好,并且使用起来更容易,更直观.

Instead of using urllib2, you can use requests. This new python lib is really well written and it's easier and more intuitive to use.

要发送json数据,您可以使用以下代码:

To send your json data you can use something like the following code:

import json
import requests
data = {'temperature':'24.3'}
data_json = json.dumps(data)
payload = {'json_payload': data_json, 'apikey': 'YOUR_API_KEY_HERE'}
r = requests.get('http://myserver/emoncms2/api/post', data=payload)

然后您可以检查r以获得http状态代码,内容等

You can then inspect r to obtain an http status code, content, etc

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

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