C# 模拟web Get,Post

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Asa_Jim/article/details/49330713

         由于经常需要模拟web Get,Post等方法,今天将这些方法顺便整理分享。

         一个不错的在线测试网站: 点击打开链接 可以模拟各种Get,Post,还可以设置body,header的参数,比较方便,强力推荐


         Get:

       

<span style="white-space:pre">	</span>public static string HttpGet(string url, NameValueCollection content, NameValueCollection headers, Encoding encode)
        {
            string errorMsg;

            var webClient = new WebClient { Encoding = encode ?? Encoding.UTF8 };
            webClient.Headers.Add(headers);

            try
            {
                webClient.QueryString.Add(content);
                return webClient.DownloadString(url);
            }
            catch (Exception ex)
            {
                errorMsg = ex.ToString();
            }
            return errorMsg;
        }
        //如果没有content和header 参数 则 new 空对象而不能为null
          Post(不上传文件)

         

         
         /// <summary>  
        /// 创建POST方式的HTTP请求
        /// </summary>  
        /// <param name="url">请求的URL</param>  
        /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>  
        /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
        /// <returns></returns>
        public static string HttpPost(string url, string parameters, CookieCollection cookies,Encoding  encoding =null)
        {
            if (encoding == null)
            {
                encoding = Encoding.UTF8;
            }
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }

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

            try
            {
                request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "POST"; 
                request.ContentType = "application/x-www-form-urlencoded";           
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; //默认IE
                request.Timeout = 4000;//4秒超时

               
                if (cookies != null)
                {
                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(cookies);
                }

                byte[] data = encoding.GetBytes(parameters);
                request.ContentLength = data.Length;
                stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);

                stream.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            var response = request.GetResponse() as HttpWebResponse;
            string xml = new StreamReader(response.GetResponseStream(), encoding).ReadToEnd();
            return xml;
        }
         参考:http://blog.csdn.net/haitaofeiyang/article/details/18362225  有完整的例子
  

               Post (带文件)

             

 /// <summary>
        /// post 数据 body 参数,支持文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeOut"></param>
        /// <param name="fileKeyName">文件名</param>
        /// <param name="filePath">文件地址</param>
        /// <param name="stringDict">body 参数列表</param>
        /// <returns></returns>
        public static string HttpPostData(string url, int timeOut, string fileKeyName,string filePath, NameValueCollection stringDict)
        {
            string responseContent;
            var memStream = new MemoryStream();
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            // 边界符
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            // 边界符
            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            // 最后的结束符
            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");
            // 设置属性
            webRequest.Method = "POST";
            webRequest.Timeout = timeOut;
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            // 写入文件
            const string filePartHeader =
                "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                 "Content-Type: application/octet-stream\r\n\r\n";
            var header = string.Format(filePartHeader, fileKeyName, filePath);
            var headerbytes = Encoding.UTF8.GetBytes(header);
            memStream.Write(beginBoundary, 0, beginBoundary.Length);
            memStream.Write(headerbytes, 0, headerbytes.Length);
            var buffer = new byte[1024];
            int bytesRead; // =0
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                memStream.Write(buffer, 0, bytesRead);
            }
            // 写入字符串的Key
            var stringKeyHeader = "\r\n--" + boundary +
                                   "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                                   "\r\n\r\n{1}\r\n";
            foreach (byte[] formitembytes in from string key in stringDict.Keys
                                             select string.Format(stringKeyHeader, key, stringDict[key])
                                                 into formitem
                                                 select Encoding.UTF8.GetBytes(formitem))
            {
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }
            // 写入最后的结束边界符
            memStream.Write(endBoundary, 0, endBoundary.Length);
            webRequest.ContentLength = memStream.Length;
            var requestStream = webRequest.GetRequestStream();
            memStream.Position = 0;
            var tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();
            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();
            var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
            using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
                                                            Encoding.GetEncoding("utf-8")))
            {
                responseContent = httpStreamReader.ReadToEnd();
            }
            fileStream.Close();
            httpWebResponse.Close();
            webRequest.Abort();
            return responseContent;
        }
        参考:http://www.suchso.com/projecteactual/csharp-HttpWebRequest-post-dll.html
                 

            

猜你喜欢

转载自blog.csdn.net/Asa_Jim/article/details/49330713
今日推荐