标签:style blog http io ar color os 使用 sp
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Net; using System.IO; using System.Text; using System.Collections.Generic; namespace WebAppTest { public class HttpTools { public static string GetRequest(string url) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "get"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using(StreamReader sr = new StreamReader(response.GetResponseStream(),Encoding.UTF8)) { string result = sr.ReadToEnd(); return result; } } public static string PostRequest(string url,Dictionary<object,object> paramList) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); StringBuilder sb = new StringBuilder(); foreach (var item in paramList) { sb.Append(item.Key + "=" + item.Value + "&"); } //将参数拼为:"name=test&pwd=123" 这种字符串格式 然后将字符串转为byte数组 最后将byte数组写入请求流中 string paramData = sb.ToString().Trim(‘&‘); byte[] data = System.Text.Encoding.UTF8.GetBytes(paramData); //设置post方式 request.Method = "post"; //这句不能少 不难post请求 得不到对应的响应结果 request.ContentType = "application/x-www-form-urlencoded"; //设置请求参数的长度 request.ContentLength = data.Length; Stream stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Close(); /** * *****************注意事项******************** * * 不管是get还是post请求最后得到的响应流不能直接stream * 不难得不到响应结果 * * * 直接使用Stream 不能获取响应的结果值 * * 要使用StreamReader才能获取响应的结果值 * * Stream stream = response.GetResponseStream(); * * byte[] data = new byte[2*1024*1024] * * int r = stream.Read(data,0,data.Length); * * string result = System.Text.Encoding.UTF8.GetString(data, 0, r); * * * **/ HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using(StreamReader sr = new StreamReader(response.GetResponseStream(),Encoding.UTF8)) { string result = sr.ReadToEnd(); return result; } } } }
标签:style blog http io ar color os 使用 sp
原文地址:http://www.cnblogs.com/zoro-zero/p/4143901.html