码迷,mamicode.com
首页 > Web开发 > 详细

HttpWebRequest 表单提交

时间:2017-05-10 19:44:21      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:encode   head   进制   time   属性   二进制   image   str   logo   

 1    /// <summary>
 2     /// http请求
 3     /// </summary>
 4     public static class ZkWebRequestHelp
 5     {
 6 
 7         /// <summary>
 8         /// 发送Htpp请求
 9         /// </summary>
10         /// <typeparam name="T"></typeparam>
11         /// <param name="url">请求的Url</param>
12         /// <param name="headPara">头部集合键值对 默认为空</param>
13         /// <param name="method">请求方法 默认get</param>
14         /// <param name="para">参数字符 默认为字符串的空</param>
15         /// <param name="contentType">请求的数据类型 </param>
16         /// <param name="timeOut">超时时间 默认15s</param>
17         /// <param name="encoding">编码方式 默认 Encoding.UTF8</param>
18         /// <returns></returns>
19         public static T SendRequest<T>(string url, string method = "get", NameValueCollection headPara = null, string para = null, string userAgent = null, string contentType = null, int timeOut = 1200, Encoding encoding = null, bool needDeserialize = true)
20         {
21             string str = SendRequestGetStr(url, method, headPara, para, userAgent, contentType, timeOut, encoding);
22             if (needDeserialize)
23             {
24                 return JsonConvert.DeserializeObject<T>(str);
25             }
26             return default(T);
27         }
28 
29 
30         /// <summary>
31         /// 发送Htpp请求
32         /// </summary>
33         /// <typeparam name="T"></typeparam>
34         /// <param name="url">请求的Url</param>
35         /// <param name="headPara">头部集合键值对 默认为空</param>
36         /// <param name="method">请求方法 默认get</param>
37         /// <param name="para">参数字符 默认为字符串的空</param>
38         /// <param name="contentType">请求的数据类型 </param>
39         /// <param name="timeOut">超时时间 默认15s</param>
40         /// <param name="encoding">编码方式 默认 Encoding.UTF8</param>
41         /// <returns></returns>
42         public static string SendRequestGetStr(string url, string method = "get", NameValueCollection headPara = null, string para = null, string userAgent = null, string contentType = null, int timeOut = 1200, Encoding encoding = null)
43         {
44             para = para ?? "";
45             var request = (HttpWebRequest)WebRequest.Create(url);
46             encoding = encoding ?? Encoding.UTF8;
47             var dataByte = encoding.GetBytes(para);//请求参数
48             request.Method = string.Compare(method, "get", StringComparison.OrdinalIgnoreCase) == 0 ? WebRequestMethods.Http.Get : WebRequestMethods.Http.Post;
49             request.Timeout = timeOut * 1000;
50             request.AllowAutoRedirect = false;
51             request.ContentLength = dataByte.Length;
52             request.ContentType = contentType ?? "application/x-www-form-urlencoded";
53             request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
54             request.UserAgent = userAgent ?? "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36";
55             if (headPara != null && headPara.Count > 0)
56             {
57                 foreach (string key in headPara)
58                 {
59                     request.Headers.Add(key, headPara[key]);
60                 }
61             }
62             if (request.Method == WebRequestMethods.Http.Post)
63             {
64                 var stream = request.GetRequestStream();
65                 stream.Write(dataByte, 0, dataByte.Length);
66                 stream.Close();
67             }
68 
69             var response = (HttpWebResponse)request.GetResponse();
70             var sr = new StreamReader(response.GetResponseStream());
71             return sr.ReadToEnd();
72         }
73 
74         public static byte[] DownloadByteArray(string url)
75         {
76             var request = (HttpWebRequest)WebRequest.Create(url);
77             request.Timeout = 10 * 1000;
78             request.AllowAutoRedirect = false;
79             request.ContentType = "application/x-www-form-urlencoded";
80             request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
81             request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36";
82             request.Method = WebRequestMethods.Http.Get;
83             var response = (HttpWebResponse)request.GetResponse();
84             using (var responseSteam = response.GetResponseStream())
85             {
86                 using (var ms = new MemoryStream())
87                 {
88                     responseSteam.CopyTo(ms);
89                     return ms.GetBuffer();
90                 }
91             }
92 
93 
94         }
95     }
public class SendFileHelper
    {
        readonly Encoding encoding = Encoding.UTF8;

        public string UploadData(string url, byte[] bytes)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = 10 * 1000;
            request.AllowAutoRedirect = false;
            request.ContentType = ContentType;
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36";
            request.Headers.Add("apptype", "2");
            request.Method = WebRequestMethods.Http.Post;
            if (request.Method == WebRequestMethods.Http.Post)
            {
                var stream = request.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();
            }
            var response = (HttpWebResponse)request.GetResponse();
            var sr = new StreamReader(response.GetResponseStream());
            return sr.ReadToEnd();
        }

        #region 组建尾部边界值
        /**/
        /// <summary>
        /// 拼接所有的二进制数组为一个数组
        /// </summary>
        /// <param name="byteArrays">数组</param>
        /// <returns></returns>
        /// <remarks>加上结束边界</remarks>
        public byte[] JoinBytes(ArrayList byteArrays)
        {
            int length = 0;
            int readLength = 0;

            // 加上结束边界
            string endBoundary = Boundary + "--\r\n"; //结束边界
            byte[] endBoundaryBytes = encoding.GetBytes(endBoundary);
            byteArrays.Add(endBoundaryBytes);

            foreach (byte[] b in byteArrays)
            {
                length += b.Length;
            }
            byte[] bytes = new byte[length];

            // 遍历复制
            //
            foreach (byte[] b in byteArrays)
            {
                b.CopyTo(bytes, readLength);
                readLength += b.Length;
            }

            return bytes;
        }
        #endregion

        #region 普通数据加入数组
        /**/
        /// <summary>
        /// 获取普通表单区域二进制数组
        /// </summary>
        /// <param name="fieldName">表单名</param>
        /// <param name="fieldValue">表单值</param>
        /// <returns></returns>
        /// <remarks>
        /// -----------------------------7d52ee27210a3c\r\nContent-Disposition: form-data; name=\"表单名\"\r\n\r\n表单值\r\n
        /// </remarks>
        public byte[] CreateFieldData(string fieldName, string fieldValue)
        {
            string textTemplate = Boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
            string text = String.Format(textTemplate, fieldName, fieldValue);
            byte[] bytes = encoding.GetBytes(text);
            return bytes;
        }
        #endregion

        #region 文件加入数组
        /**/
        /// <summary>
        /// 获取文件上传表单区域二进制数组
        /// </summary>
        /// <param name="fieldName">表单名</param>
        /// <param name="filename">文件名</param>
        /// <param name="contentType">文件类型</param>
        /// <param name="contentLength">文件长度</param>
        /// <param name="stream">文件流</param>
        /// <returns>二进制数组</returns>
        public byte[] CreateFieldData(string fieldName, string filename, byte[] fileBytes, string contentType = "application/octet-stream")
        {
            string end = "\r\n";
            string textTemplate = Boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";

            // 头数据
            string data = String.Format(textTemplate, fieldName, filename, contentType);
            byte[] bytes = encoding.GetBytes(data);



            // 尾数据
            byte[] endBytes = encoding.GetBytes(end);

            // 合成后的数组
            byte[] fieldData = new byte[bytes.Length + fileBytes.Length + endBytes.Length];

            bytes.CopyTo(fieldData, 0); // 头数据
            fileBytes.CopyTo(fieldData, bytes.Length); // 文件的二进制数据
            endBytes.CopyTo(fieldData, bytes.Length + fileBytes.Length); // \r\n

            return fieldData;
        }
        #endregion

        #region 属性
        public string Boundary
        {
            get
            {
                string[] bArray, ctArray;
                string contentType = ContentType;
                ctArray = contentType.Split(‘;‘);
                if (ctArray[0].Trim().ToLower() == "multipart/form-data")
                {
                    bArray = ctArray[1].Split(‘=‘);
                    return "--" + bArray[1];
                }
                return null;
            }
        }

        public string ContentType
        {
            get
            {
                return "multipart/form-data; boundary=---------------------------7d5b915500cee";
            }
        }
        #endregion
    }

  使用示例(表单提交):

 var byteArray = ZkWebRequestHelp.DownloadByteArray("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png");//获取文件流
            var sendFile = new SendFileHelper();
            ArrayList bytesArray = new ArrayList();
            // 普通表单
            bytesArray.Add(sendFile.CreateFieldData("name", "张三"));//普通数据
            bytesArray.Add(sendFile.CreateFieldData("age", "18"));//普通数据
            bytesArray.Add(sendFile.CreateFieldData("file", "123.jpg", byteArray));//文件上传
            var bytes = sendFile.JoinBytes(bytesArray);
            sendFile.UploadData("http://localhost:16311/api/Authorization/UploadData", bytes);

  

HttpWebRequest 表单提交

标签:encode   head   进制   time   属性   二进制   image   str   logo   

原文地址:http://www.cnblogs.com/q975261413/p/6837465.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!