C# server form post
以前用 form post的 Content-Type通常都是 "application/x-www-form-urlencoded",今天才注意到用 server post "multipart/form-data"有些小細節;簡單的結論:
- "application/x-www-form-urlencoded":用鍵值對傳送純文字(key1=value1&ke2=value2)
-
"multipart/form-data;":The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data. 格式比較複雜,直接看 code XD(update: 2015-10-19 content type指定的 boundary要略過開頭的 "--")
public enum ContentType { Default, Multipart, JSON } public class Common { public static string GetRemoteData(string url, ContentType contentType, System.Web.Mvc.FormCollection formData, string jsonData, string method = "POST") { HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); req.Method = method; req.Accept = "*/*"; string postData = string.Empty; List
dataList = new List (); switch (contentType) { case ContentType.Multipart: // http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2 string boundary = string.Format("--{0}", Guid.NewGuid()); foreach (var key in formData.AllKeys) { dataList.Add(boundary); dataList.Add(string.Format("Content-Disposition: form-data; name=\"{0}\"", key)); dataList.Add(string.Empty); dataList.Add(formData[key]); } dataList.Add(boundary + "--"); postData = string.Join("\r\n", dataList);// "CR LF" req.ContentType = "multipart/form-data; boundary=" + boundary.Substring(2); break; case ContentType.JSON: postData = jsonData; req.ContentType = "application/json"; break; case ContentType.Default: default: foreach (var key in formData.AllKeys) { dataList.Add(string.Format("{0}={1}", key, formData[key])); } postData = string.Join("&", dataList); req.ContentType = "application/x-www-form-urlencoded"; break; } string response = string.Empty; try { byte[] myData = Encoding.UTF8.GetBytes(postData); req.ContentLength = myData.Length; using (Stream streamOut = req.GetRequestStream()) { streamOut.Write(myData, 0, myData.Length); } using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream())) { response = streamIn.ReadToEnd(); } } catch { } return response; } } // 使用: Common.GetRemoteData("http://localhost:49801/", ContentType.Default, formData: formData, jsonData: null);