string result =GetRequest("http://localhost:32163/DuoBao/ajax.aspx", "time=5"); //如果有好几个参数可以在后面加,如: time=5&b=1&c=5
/// <summary> /// 获得post请求后响应的数据 /// </summary> /// <param name="postUrl">请求地址</param> /// <param name="data">请求带的数据</param> /// <returns>响应内容</returns>
public string GetRequest(string postUrl, string data) { string result = ""; try { //命名空间System.Net下的HttpWebRequest类 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl); //参照浏览器的请求报文 封装需要的参数 这里参照ie9 //浏览器可接受的MIME类型 request.Accept = "text/plain, */*; q=0.01"; //包含一个URL,用户从该URL代表的页面出发访问当前请求的页面 //浏览器类型,如果Servlet返回的内容与浏览器类型有关则该值非常有用 request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)"; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; //请求方式 request.Method = "POST"; //是否保持常连接 request.KeepAlive = false; request.Headers.Add("Accept-Encoding", "gzip, deflate"); //表示请求消息正文的长度 request.ContentLength = data.Length; Stream postStream = request.GetRequestStream(); byte[] postData = Encoding.UTF8.GetBytes(data); //将传输的数据,请求正文写入请求流 postStream.Write(postData, 0, postData.Length); postStream.Dispose(); //响应 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //判断响应的信息是否为压缩信息 若为压缩信息解压后返回 if (response.ContentEncoding == "gzip") { MemoryStream ms = new MemoryStream(); GZipStream zip = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress); byte[] buffer = new byte[1024]; int l = zip.Read(buffer, 0, buffer.Length); while (l > 0) { ms.Write(buffer, 0, l); l = zip.Read(buffer, 0, buffer.Length); } ms.Dispose(); zip.Dispose(); result = Encoding.UTF8.GetString(ms.ToArray()); } return result; } catch (Exception) { throw; } }
///请求的页面
public override void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //接收参数 string time = context.Request["time"]; if (!string.IsNullOrEmpty(time)) { //调用方法 }
context.Response.Write("2");//返回参数 }
来源 http://www.cnblogs.com/lyl6796910/p/3722280.html
|
请发表评论