如何将 POST 请求作为 JSON 发送? [英] How do I send a POST request as a JSON?

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

问题描述

data = {
        'ids': [12, 3, 4, 5, 6 , ...]
    }
    urllib2.urlopen("http://abc.com/api/posts/create",urllib.urlencode(data))

我想发送一个 POST 请求,但其中一个字段应该是一个数字列表.我怎样才能做到这一点 ?(JSON?)

I want to send a POST request, but one of the fields should be a list of numbers. How can I do that ? (JSON?)

推荐答案

如果您的服务器期望 POST 请求是 json,那么您需要添加一个标头,并序列化您的请求的数据...

If your server is expecting the POST request to be json, then you would need to add a header, and also serialize the data for your request...

Python 2.x

import json
import urllib2

data = {
        'ids': [12, 3, 4, 5, 6]
}

req = urllib2.Request('http://example.com/api/posts/create')
req.add_header('Content-Type', 'application/json')

response = urllib2.urlopen(req, json.dumps(data))

Python 3.x

https://stackoverflow.com/a/26876308/496445

如果您不指定标题,它将是默认的 application/x-www-form-urlencoded 类型.

If you don't specify the header, it will be the default application/x-www-form-urlencoded type.

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

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