[工具类]模拟请求时提交大字符串

写在前面

开发中也会经常用到模拟请求的东东,有时候提交的数据比较大,一般的方式就不行了,这个时候,下面的方式就会更好的解决你的问题。

方法

提交的数据比较大的时候,就会用到这个方法,当然可以对该方法进行修改一下,也可以提交文件。

        /// <summary>
        /// 提交大数据量
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string PostBigString(string url, string postData)
        {
            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 = 40000;
            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, "", "");
            var headerbytes = Encoding.UTF8.GetBytes(header);

            memStream.Write(beginBoundary, 0, beginBoundary.Length);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            var buffer = Encoding.UTF8.GetBytes(postData);


            // 写入字符串的Key  
            var stringKeyHeader = "\r\n--" + boundary +
                                   "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                                   "\r\n\r\n{1}\r\n";
            string formitem = string.Format(stringKeyHeader, "value", postData);
            byte[] formitembytes = 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();
            }


            httpWebResponse.Close();
            webRequest.Abort();

            return responseContent;
        }

普通的模拟post请求的方法

        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url">请求的地址</param>
        /// <param name="postdata">参数</param>
        /// <returns></returns>
        public static string PostString(string url, string postdata)
        {
            string strJson = string.Empty;
            try
            {
                byte[] buffer = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Method = "POST";
                request.Accept = "application/json;charset:utf-8";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = buffer.Length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(buffer, 0, buffer.Length);
                }
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        strJson = sr.ReadToEnd();
                    }
                }
                return strJson;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

对于一般的post请求,上面的方法已经能解决了,但是对应提交的数据比较大的时候,上面的这个方法就会显得力不从心了。

总结

在项目中,经常用到模拟请求某个接口的情况,不想每次都去f12查看请求头的东西,这也算总结一下,方便以后的使用。

posted @ 2015-11-19 14:47  wolfy  阅读(557)  评论(0编辑  收藏  举报