POST方法提交数据,一种众所周知的方法:
html页面中使用form表单提交,接收方法,使用Request.Form[""]或Request.QueryString[""]来获取。
这里介绍此外一种POST方法和接收方法,就是将整个数据作为插手到数据流中提交和接收
接收方法:
Stream s = System.Web.HttpContext.Current.Request.InputStream; byte[] b = new byte[s.Length]; s.Read(b, 0, (int)s.Length); return Encoding.UTF8.GetString(b);
只需要从input Stream中读取byte数据,然后转为string,再解析即可。如果要答复响应动静只需要用:Response.Write() 输出即可(和普通的页面输出一样)。
主动POST发送方法:
HttpWebRequest webrequest = (HttpWebRequest)HttpWebRequest.Create(url); webrequest.Method = "post"; byte[] postdatabyte = Encoding.UTF8.GetBytes(postData); webrequest.ContentLength = postdatabyte.Length; Stream stream; stream = webrequest.GetRequestStream(); stream.Write(postdatabyte, 0, postdatabyte.Length); stream.Close(); using (var httpWebResponse = webrequest.GetResponse()) using (StreamReader responseStream = new StreamReader(httpWebResponse.GetResponseStream())) { String ret = responseStream.ReadToEnd(); T result = XmlDeserialize<T>(ret); return result; }
使用HttpClient东西发送
public static string PostXmlResponse(string url, string xmlString) { HttpContent httpContent = new StringContent(xmlString); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpClient httpClient = new HttpClient(); HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; if (response.IsSuccessStatusCode) { Task<string> t = response.Content.ReadAsStringAsync(); return t.Result; } return string.Empty; }
从代码中可以看出仅仅是将字符串转为byte[] 类型,并插手到请求流中,进行请求即可到达POST效果,,该种POST方法与上边所提到的接收方法彼此共同使用。
下面一种方法是以键值对的方法主动POST传输的。
/// <summary> /// 倡议httpPost 请求,可以上传文件 /// </summary> /// <param>请求的地点</param> /// <param>文件</param> /// <param>表单数据</param> /// <param>编码</param> /// <returns></returns> public static string PostResponse(string url, UpLoadFile[] files, Dictionary<string, string> input, Encoding endoding) { string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "multipart/form-data; boundary=" + boundary; request.Method = "POST"; request.KeepAlive = true; //request.Credentials = CredentialCache.DefaultCredentials; request.Expect = ""; MemoryStream stream = new MemoryStream(); byte[] line = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); byte[] enterER = Encoding.ASCII.GetBytes("\r\n"); ////提交文件 if (files != null) { string fformat = "Content-Disposition:form-data; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n"; foreach (UpLoadFile file in files) { stream.Write(line, 0, line.Length); //项目分隔断绝分手符 string s = string.Format(fformat, file.Name, file.FileName, file.Content_Type); byte[] data = Encoding.UTF8.GetBytes(s); stream.Write(data, 0, data.Length); stream.Write(file.Data, 0, file.Data.Length); stream.Write(enterER, 0, enterER.Length); //添加\r\n } } //提交文本字段 if (input != null) { string format = "--" + boundary + "\r\nContent-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}\r\n"; //自带项目分隔断绝分手符 foreach (string key in input.Keys) { string s = string.Format(format, key, input[key]); byte[] data = Encoding.UTF8.GetBytes(s); stream.Write(data, 0, data.Length); } } byte[] foot_data = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n"); //项目最后的分隔断绝分手符字符串需要带上-- stream.Write(foot_data, 0, foot_data.Length); request.ContentLength = stream.Length; Stream requestStream = request.GetRequestStream(); //写入请求数据 stream.Position = 0L; stream.CopyTo(requestStream); // stream.Close(); requestStream.Close(); try { HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); try { using (var responseStream = response.GetResponseStream()) using (var mstream = new MemoryStream()) { responseStream.CopyTo(mstream); string message = endoding.GetString(mstream.ToArray()); return message; } } catch (Exception ex) { throw ex; } } catch (WebException ex) { //response = (HttpWebResponse)ex.Response; //if (response.StatusCode == HttpStatusCode.BadRequest) //{ // using (Stream data = response.GetResponseStream()) // { // using (StreamReader reader = new StreamReader(data)) // { // string text = reader.ReadToEnd(); // Console.WriteLine(text); // } // } //} throw ex; } } catch (Exception ex) { throw ex; } }
通过两种主动POST提交 的代码可以看出,其主要区别在于发送前的数据格局 ContentType 的值。
下面列举几种常用的ContentType 值,并简述他们的区别