如何在http请求中发送JSON数据? [英] How does JSON data get sent in an http request?

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

问题描述

假设我在下面发出http请求,以更新mongoDB数据库中的某些记录:

Let's say I'm making the http request below, to update some record in a mongoDB database:

输入
http://dev.mycompany.co/ping
{"id":4432,"name":"Jane Doe",产品":[{"id":287},{"id":434}]}

PUT
http://dev.mycompany.co/ping
{"id":4432, "name":"Jane Doe", "products":[ {"id":287}, {"id":434} ] }

请注意,上述JSON的"products"属性内有两个对象组成的数组.我有通过Fiddler和我编写的ruby脚本以这种通用格式发送的数据.

Notice that there is an array of two objects inside the "products" property of the JSON above. I have data that is being sent in this general format, both through Fiddler and through a ruby script I've written.

通过Fiddler发送时,我的JSON中的数据已正确解析并更新到我的数据库中.通过我的ruby脚本发送时,正确解析了JSON中的数据.我一直在试图找出原因.现在,我想知道当将JSON与http请求一起发送时如何实际发送数据.有人可以指出我正确的方向吗?

When sent through Fiddler, my data in the JSON is correctly parsed and updated into my database. When sent through my ruby script, the data in the JSON is not parsed correctly. I've been trying to figure out why this is. Now, I'm wondering how data is actually sent when a JSON is sent along with an http request. Can someone point me in the right direction?

推荐答案

问了一些关于SO的问题并进行了很多研究之后,我得出了以下结论.

After asking a few other questions on SO and doing a bunch more research, I've arrived at the following conclusions.

问:如何在http请求中发送JSON数据?

A:这取决于您如何在请求中发送JSON数据(内容类型是什么)

A: It depends on how you are sending the JSON data in the request (what is the content-type)

我遇到了两种发送JSON数据的方式.

I've encountered two ways that JSON data is sent.

  1. 使用内容类型 application/json

使用此内容类型,JSON数据按原样发送.文字JSON数据存储为字符串,并与请求一起发送.如果您的JSON很复杂,带有嵌套的对象和数组等,这可能就是您想要的.有关使用Ruby的Net/HTTP发送嵌套JSON的工作示例,请参见

With this content-type, JSON data is sent literally as-is. The literal JSON data is stored as a string and sent with the request. If your JSON is complex, with nested objects and arrays and such, this is probably what you want. For a working example of sending nested JSONs using Ruby's Net/HTTP, see the answer on this SO question I asked.

使用内容类型 x-www-form-urlencoded

这通常是发送Ruby的Net/HTTP请求的方式.这些请求的形式类似于: id = 343?entity = Microsoft?foo = bar .除非您具有复杂的JSON,否则此内容类型很好.

This is how Ruby's Net/HTTP requests typically get sent out. The form of these requests is something like: id=343?entity=Microsoft?foo=bar. This content-type is fine until you have a complex JSON.

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

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