/// <summary> /// POST请求与获取结果 /// </summary> public string HttpPost(string Url, string postDataStr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postDataStr.Length; StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII); writer.Write(postDataStr); writer.Flush(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1) { encoding = "UTF-8"; //默认编码 } StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); string retString = reader.ReadToEnd(); return retString; }
调用方法
HttpPost("http://www.luofenming.com/Getdata.ashx", "userName= userName &Password=password"); //注意 URL是一个服务地址格式不要写错了
以上是客户端,下面是服务端 http://www.luofenming.com/Getdata.ashx代码
<%@ WebHandler Language="C#" Class="getData" %> using System; using System.Web; public class getData : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; string userName = context.Request["userName"];//接收客户端发来的数据userName=123&Password=456 string Password = context.Request["password"]; context.Response.Write("接收成功,内容为userName:"+userName+"passWord:"+Password);//响应发送端 } public bool IsReusable { get { return false; } } }