码迷,mamicode.com
首页 > Windows程序 > 详细

C# Post 使用(multipart/form-data)请求数据

时间:2021-07-05 18:04:31      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:ali   odi   datetime   --   get   eth   data   type   sharp   

 
public static string HttpPostMultipartFormData(string url, NameValueCollection kVDatas, string method = WebRequestMethods.Http.Post, string encoding= "UTF-8", int timeOut = -1) { string resultStr = ""; try { string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = Encoding.GetEncoding(encoding).GetBytes("\r\n--" + boundary + "\r\n"); byte[] endbytes = Encoding.GetEncoding(encoding).GetBytes("\r\n--" + boundary + "--\r\n"); //1.HttpWebRequest HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "multipart/form-data; boundary=" + boundary; request.Method = method; request.KeepAlive = true; request.Timeout = timeOut; using (Stream stream = request.GetRequestStream()) { //1.1 key/value string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; if (kVDatas != null) { foreach (string key in kVDatas.Keys) { stream.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, key, kVDatas[key]); byte[] formitembytes = Encoding.GetEncoding(encoding).GetBytes(formitem); stream.Write(formitembytes, 0, formitembytes.Length); } } stream.Write(endbytes, 0, endbytes.Length); } //2.WebResponse using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader stream = new StreamReader(response.GetResponseStream())) { resultStr = stream.ReadToEnd(); } } } catch (WebException ex) { var errorSr = new StreamReader(ex.Response.GetResponseStream()); resultStr = errorSr.ReadToEnd(); } return resultStr; }

 

C# Post 使用(multipart/form-data)请求数据

标签:ali   odi   datetime   --   get   eth   data   type   sharp   

原文地址:https://www.cnblogs.com/LuoCore/p/14966175.html

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