C# 发送HttpWebRequest,得到HttpWebResponse
using System; using System.IO; using System.Net; using System.Text; using System.Web; namespace JasonLibrary { public class HttpHelpler { public string Url { get; set; } public string Data { get; set; } public HttpHelpler(string url) { this.Url = url; } public HttpHelpler(string url, string data) { this.Url = url; this.Data = data; } public string ExecutePost() { try { HttpWebRequest myRequest = HttpWebRequest.Create(Url) as HttpWebRequest; myRequest.Method = "POST"; myRequest.ContentType = "application/json;charset=UTF-8"; myRequest.ReadWriteTimeout = 30000; byte[] data = Encoding.UTF8.GetBytes(Data); myRequest.ContentLength = data.Length; Stream myStream = myRequest.GetRequestStream(); myStream.Write(data, 0, data.Length); myStream.Close(); HttpWebResponse myResponse = myRequest.GetResponse() as HttpWebResponse; StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); string res = sr.ReadToEnd(); return res; } catch { return null; } } public string ExecuteGet() { HttpWebRequest myRequest = HttpWebRequest.Create(Url) as HttpWebRequest; myRequest.Method = "GET"; myRequest.ReadWriteTimeout = 30000; HttpWebResponse myResponse = null; try { myResponse = myRequest.GetResponse() as HttpWebResponse; StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); string res = sr.ReadToEnd(); return res; } catch (WebException ex) { myResponse = ex.Response as HttpWebResponse; using (Stream errData = myResponse.GetResponseStream()) { using (StreamReader sr = new StreamReader(errData)) { string res = sr.ReadToEnd(); return res; } } } } } }