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

 
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)请求数据

上一篇:Photoshop磨皮教程视频美女美白


下一篇:Koa与Node.js开发实战(1)——Koa安装搭建(视频演示)