【问题标题】:Sending JSON request with Python使用 Python 发送 JSON 请求
【发布时间】:2025-12-19 04:55:06
【问题描述】:

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

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

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

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 数据添加到请求中?

谢谢!

【问题讨论】:

    标签: python json


    【解决方案1】:

    您可以使用requests,而不是使用urllib2。这个新的 python 库写得非常好,使用起来更简单、更直观。

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

    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 状态代码、内容等

    【讨论】:

    • 感谢您的回复!有没有一种方法可以用来打印实际的获取请求字符串?服务器响应“需要有效的写入 apikey”,但我使用的是在浏览器中工作的相同密钥。
    • 是的,您可以为此使用事件挂钩。实际上,请求文档包含一个示例,在发送请求之前打印 url:docs.python-requests.org/en/latest/user/advanced/#event-hooks
    • 嗨 Simao,这使我能够查看参数,但是我需要做什么才能查看发送到服务器的实际完整请求字符串,例如'myserver/emoncms2/api/post?apikey=xxxxxxxxxxxxx&json={功率:290.4,温度:19.4}
    • 好的,我想我知道如何查看详细请求了,我需要将verbose logging 重定向到标准输出。
    • 我尝试使用文档中描述的钩子,似乎正在发送数据。请注意,传递给回调的 args 变量包含的不仅仅是 url,它是一个完整的 Requests GET 对象。此外,在您的原始帖子中,您提到您正在尝试获取您的资源,但在您的最后一个日志行中,您显示了一个 POST 请求。
    【解决方案2】:

    尽管这不能完全回答 OP 的问题,但这里应该提到 requests 模块有一个 json 选项,可以像这样使用:

    import requests
    
    requests.post(
        'http://myserver/emoncms2/api/post?apikey=xxxxxxxxxxxxx',
        json={"temperature": "24.3"}
    )
    
    

    相当于卷曲:

    curl 'http://myserver/emoncms2/api/post?apikey=xxxxxxxxxxxxx' \
        -H 'Content-Type: application/json' \
        --data-binary '{"temperature":"24.3"}'
    
    

    【讨论】:

    • 需要注意的是,requests json 选项将数据包含在请求正文中,而不是直接在 URI 中。
    【解决方案3】:

    也许问题在于json.dumps 放入了",而在您输入url 的json 中没有"s。 例如:

    data = {'temperature':'24.3'}
    print json.dumps(data)
    

    打印:

    {"temperature": "24.3"}

    而不是:

    {temperature: 24.3}

    就像你输入你的网址一样。

    解决这个问题(容易出问题)的一种方法是:

    json.dumps(data).replace('"', '')
    

    【讨论】:

    • 感谢您的回复。我已经测试了在浏览器中使用键和值的引号发送请求,它仍然可以正常工作。我似乎遇到的主要问题是我的 python 脚本没有正确发送 apikey 数据。
    • 把你的代码改成这样怎么样:params = urllib.urlencode({'apikey':'xxxxxxx', 'json':{'temperature':'24.3'}}) \ urllib2.urlopen(host + '?' + params)