GET 和 POST 请求的优缺点

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了GET 和 POST 请求的优缺点相关的知识,希望对你有一定的参考价值。

参考技术A (1)post更安全(不会作为url的一部分,不会被缓存、保存在服务器日志、以及浏览器浏览记录中)
(2)post发送的数据更大(get有url长度限制)
(3)post能发送更多的数据类型(get只能发送ASCII字符)
(4)post比get慢
(5)post用于修改和写入数据,get一般用于搜索排序和筛选之类的操作
(6)get请求的是静态资源,则会缓存,如果是数据,则不会缓存

1.post请求包含更多的请求头
因为post需要在请求的body部分包含数据,所以会多了几个数据描述部分的首部字段(如:content-type),这其实是微乎其微的。
2.最重要的一条,post在真正接收数据之前会先将请求头发送给服务器进行确认,然后才真正发送数据

(1)浏览器请求tcp连接(第一次握手)
(2)服务器答应进行tcp连接(第二次握手)
(3)浏览器确认,并发送post请求头(第三次握手,这个报文比较小,所以http会在此时进行第一次数据发送)
(4)服务器返回100 Continue响应
(5)浏览器发送数据
(6)服务器返回200 OK响应

(1)浏览器请求tcp连接(第一次握手)
(2)服务器答应进行tcp连接(第二次握手)
(3)浏览器确认,并发送get请求头和数据(第三次握手,这个报文比较小,所以http会在此时进行第一次数据发送)
(4)服务器返回200 OK响应
也就是说,目测get的总耗是post的2/3左右,这个口说无凭,网上已经有网友进行过测试。

(1)http协议并未规定get和post的长度限制
(2)get的最大长度限制是因为浏览器和web服务器限制了URL的长度
(3)不同的浏览器和web服务器,限制的最大长度不一样
(4)要支持IE,则最大长度为2083byte,若支持Chrome,则最大长度8182byte

http请求POST和GET调用接口以及反射动态调用Webservices类

此代码是API、WebSrvices动态调用的类,做接口调用时很实用。

Webservices动态调用使用反射的方式很大的缺点是效率低,若有更好的动态调用webservices方法,望各位仁兄不吝贴上代码。

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Collections.Generic;
using System.CodeDom.Compiler;
using System.Web.Services.Description;
using System.CodeDom;
using Microsoft.CSharp;
/*********************
* 描述:提供http、POST和GET、Webservices动态访问远程接口
 * *******************/
namespace Demo
{
    public static class HttpHelper
    {
        ///  
        /// 有关HTTP请求的辅助类
        /// 
        private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";//浏览器 
        private static Encoding requestEncoding = System.Text.Encoding.UTF8;//字符集 
  #region 创建GET方式的HTTP请求
        ///
        /// 创建GET方式的HTTP请求   
        ///
        /// 接口URL
        /// 接口URL的参数
        /// 调用接口返回的信息
        ///
        public static bool HttpGet(string url, Dictionary dctParam, out string HttpWebResponseString)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }

            HttpWebResponseString = "";

 

            HttpWebRequest request = null;

            Stream stream = null;//用于传参数的流 

            HttpWebResponse httpWebResponse = null;

  try
            {
                int i = 0;
                StringBuilder buffer = new StringBuilder();
                if (!(dctParam == null))
                {
                    foreach (string key in dctParam.Keys)
                    {
                        if (i > 0)
                        {
                            buffer.AppendFormat("&{0}={1}", key, (dctParam[key]));
                        }
                        else
                        {
                            buffer.AppendFormat("{0}={1}", key, (dctParam[key]));
                        }
                        i++;
                    }
                    url = url + "?" + buffer.ToString();
                }

                request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "GET";//传输方式  
                request.ContentType = "application/x-www-form-urlencoded";//协议
                request.UserAgent = DefaultUserAgent;//请求的客户端浏览器信息,默认IE 
                request.Timeout = 6000;//超时时间,写死6秒
                request.KeepAlive = false;
                //DefaultConnectionLimit是默认的2,而当前的Http的connection用完了,导致后续的GetResponse或GetRequestStream超时死掉
                System.Net.ServicePointManager.DefaultConnectionLimit = 50;
                request.ServicePoint.Expect100Continue = false;
                httpWebResponse = request.GetResponse() as HttpWebResponse;
                HttpWebResponseString = ReadHttpWebResponse(httpWebResponse);
                return true;
            }
            catch (Exception ee)
            {
                HttpWebResponseString = ee.ToString();
                return false;
            }
  finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
                if (request != null)
                {
request.Abort(); request = null; } if (httpWebResponse != null) { httpWebResponse.Close(); httpWebResponse = null; } } } #endregion #region 创建POST方式的HTTP请求 /// /// 创建POST方式的HTTP请求 /// /// 接口URL /// 接口URL的参数 /// 调用接口返回的信息 /// public static bool HttpPost(string url, Dictionary dctParam, out string HttpWebResponseString) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } HttpWebResponseString = ""; HttpWebRequest request = null; Stream stream = null;//用于传参数的流 try { url = EncodePostData(url); request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST";//传输方式 request.ContentType = "application/x-www-form-urlencoded";//协议 request.UserAgent = DefaultUserAgent;//请求的客户端浏览器信息,默认IE request.Timeout = 6000;//超时时间,写死6秒 //DefaultConnectionLimit是默认的2,而当前的Http的connection用完了,导致后续的GetResponse或GetRequestStream超时死掉 System.Net.ServicePointManager.DefaultConnectionLimit = 50; request.ServicePoint.Expect100Continue = false; //如果需求POST传数据,转换成utf-8编码 byte[] Data = ParamDataConvert(dctParam); if (!(Data == null)) { string s = requestEncoding.GetString(Data); stream = request.GetRequestStream(); stream.Write(Data, 0, Data.Length); } HttpWebResponse HttpWebResponse = request.GetResponse() as HttpWebResponse; HttpWebResponseString = ReadHttpWebResponse(HttpWebResponse); return true; } catch (Exception ee) { HttpWebResponseString = ee.ToString(); return false; } finally { if (stream != null) { stream.Close(); } } } #endregion #region 反射动态调用WebServices /// /// 反射动态调用WebServices /// /// Webservices地址,以?WSDL结尾 /// 调用的方法 /// 调用方法的参数 /// public static object InvokeWebService(string url, string methodname, object[] args) { string @namespace = "Demo";//本页的命名空间 try { //获取WSDL WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace); //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider csc = new CSharpCodeProvider(); CSharpCodeProvider icc = new CSharpCodeProvider(); //设定编译参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译代理类 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type[] types = assembly.GetTypes(); Type t = types[0]; object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return mi.Invoke(obj, args); } catch (Exception ex) { } return null; } #endregion /// /// 接口参数转换 /// /// 接口参数集合包 /// private static byte[] ParamDataConvert(Dictionary dctParam) { if (dctParam == null) return null; try { Encoding requestEncoding = System.Text.Encoding.UTF8;//字符集 StringBuilder buffer = new StringBuilder(); int i = 0; foreach (string key in dctParam.Keys) { if (i > 0) { buffer.AppendFormat("&{0}={1}", key, (dctParam[key])); } else { buffer.AppendFormat("{0}={1}", key, (dctParam[key])); } i++; } string PostData = buffer.ToString(); byte[] data = requestEncoding.GetBytes(buffer.ToString()); return data; } catch (Exception ex) { } return null; } /// /// 获取数据 /// /// 响应对象 /// </returns> public static string ReadHttpWebResponse(HttpWebResponse HttpWebResponse) { Stream responseStream = null; StreamReader sReader = null; String value = null; try { // 获取响应流 responseStream = HttpWebResponse.GetResponseStream(); // 对接响应流(以"utf-8"字符集) sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); // 开始读取数据 value = sReader.ReadToEnd(); } catch (Exception ee) { throw ee; } finally { //强制关闭 if (sReader != null) { sReader.Close(); } if (responseStream != null) { responseStream.Close(); } if (HttpWebResponse != null) { HttpWebResponse.Close(); } } return value; } public static string EncodePostData(string Data) { string EncodeData = HttpUtility.UrlDecode(Data); return EncodeData; } } }

  

以上是关于GET 和 POST 请求的优缺点的主要内容,如果未能解决你的问题,请参考以下文章

浅谈WebService SOAPRestfulHTTP(post/get)请求

(gin框架拓展)两种 HTTP 请求方法:GET 和 POST

PHP中put和post区别

关于Get和Post的学习笔记

java 知识点突击-(141-150)

ajax面试题大全