How does JSON data get sent in an http request?

2019-09-12 13:42发布

问题:

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

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

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.

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?

回答1:

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

Q: How does JSON data get sent in an http request?

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

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

  1. Sent using content-type application/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.

  2. Sent using content-type x-www-form-urlencoded

    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.