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 name="url">请求的地址</param>