When submitting data to an interface through POST, you will often encounter the following sentence:

webClient.Headers.Add("Content-Type", "application/json");
Copy the code

or

webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
Copy the code

Which way should it be?

The answer has to do with the format of the arguments we submit.

If page forms are submitted, “Application/X-www-form-urlencoded”; If it’s JSON (to deserialize to a string), it’s “application/ JSON “.

For “Application/X-www-form-urlencoded”, its parameter organization form is key-value pair, similar to get parameter form: name= three &sex= male &tel=5354169, and JSON is known as:

{name:" Zhang SAN ", sex:" male ", tel:"5354169",}Copy the code

So, if you pass json and your header is “application/ X-www-form-urlencoded “, Or if the “Content-Type” is not declared (which seems to default to “Application/X-www-form-urlencoded”), the server will not get the submitted data. The data was sent, but it couldn’t be read.

And vice versa.


In addition, if the submitted data contains Chinese characters and the encoding is different from that of the server, the server may not receive the submitted data.


2019.06.20 Which format is used may also depend on the server side. There was a situation today where you had to use key-value pairs instead of JSON. JSON returns an error:

Unable to read data from transport connection: remote host forced to close an existing connectionCopy the code

“Application/X-www-form-urlencoded” is normal. Logically, it should work both ways, and we’ve tried this many times before.

Similar code:

        string postData = "value=a";
        byte[] bytes = Encoding.UTF8.GetBytes(postData);
        WebClient client = new WebClient();
        client.Headers.Add("Content-Type"."application/x-www-form-urlencoded");
        client.Headers.Add("ContentLength", postData.Length.ToString());
        Encoding enc = Encoding.GetEncoding("UTF-8");
        byte[] responseData = client.UploadData("http://localhost:28450/api/values"."POST", bytes);
        string re = enc.GetString(responseData);
Copy the code