application/json 和 application/x-www-form-urlencoded的区别

    public static string HttpPost(string url, string body)
    {
        //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
        Encoding encoding = Encoding.UTF8;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.Accept = "text/html, application/xhtml+xml, */*";
        request.ContentType = "application/x-www-form-urlencoded";//以键值对形式key1=value1&key2=value2的方式发送到服务器
        //request.ContentType = "application/json";//以标准的json格式的方式发送到服务器


        byte[] buffer = encoding.GetBytes(body);
        request.ContentLength = buffer.Length;
        request.GetRequestStream().Write(buffer, 0, buffer.Length);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
        {
            return reader.ReadToEnd();
        }
    }

application/x-www-form-urlencoded方式是以键值对形式key1=value1&key2=value2的方式发送到服务器,这种方式的好处就是浏览器都支持,在请求发送过程中会对数据进行序列化处理。
application/json方式是以标准的json格式的方式发送到服务器,,随着json规范的越来越流行,并且浏览器支持程度原来越好,许多开发人员易application/json作为请求content-type,告诉服务器请求的主题内容是json格式的字符串,服务器端会对json字符串进行解析,这种方式的好处就是前端人员不需要关心数据结构的复杂度,只要是标准的json格式就能提交成功,application/json数据格式越来越得到开发人员的青睐。

猜你喜欢

转载自www.cnblogs.com/cuihongyu3503319/p/9171952.html