1.将get获取的数据,UrlDecode后返回
public static string SendGet(string url) { HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); httpWebRequest.Method = "GET"; HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse; Stream stream = httpWebResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(stream, Encoding.UTF8); string strOut = streamReader.ReadToEnd(); httpWebResponse.Close(); strOut = HttpUtility.UrlDecode(strOut); return strOut; }
2.post请求,StreamReader方法获取ResponseStream中的信息
public static string SendPost(string data, string url, string contentType) { string content = string.Empty; HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest; httpWebRequest.AllowAutoRedirect = true; httpWebRequest.Method = "POST"; httpWebRequest.ContentType = contentType; using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream())) { sw.Write(data); } HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse; using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream())) { content = sr.ReadToEnd(); } return content; }
3.post请求,通过Stream.Read方法获取ResponseStream中的信息
public static String RequestUrl(String url, byte[] data, String method = "POST") { try { WebRequest request = WebRequest.Create(url); request.Method = method; request.ContentType = "application/x-www-form-urlencoded"; if (data != null && data.Length > 0) { request.ContentLength = data.Length; Stream newStream = request.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close(); } else { request.ContentLength = 0; } WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); MemoryStream ms = new MemoryStream(); long ChunkSize = 1024; byte[] buffer = new byte[ChunkSize]; long dataLengthToRead = response.ContentLength;//获取响应数据的总大小 while (dataLengthToRead > 0) { int lengthRead = stream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小 ms.Write(buffer, 0, lengthRead); dataLengthToRead = dataLengthToRead - lengthRead; } stream.Close(); response.Close(); string responseText = Encoding.UTF8.GetString(ms.ToArray()); return responseText; } catch (Exception ex) { return ex.Message; } }