httpPost 方式发送请求 不带参数
1 /// <summary> 2 /// 没有参数的post请求 3 /// </summary> 4 public void HttpPostNoParam() 5 { 6 string Url = "请求地址"; 7 HttpWebRequest request = WebRequest.CreateHttp(Url); 8 request.Method = "POST"; 9 request.ContentType = "application/x-www-form-urlencoded"; 10 Stream myRequestStream = request.GetRequestStream(); 11 StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312")); 12 myStreamWriter.Close(); 13 myRequestStream.Close(); 14 15 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 16 Stream myResponseStream = response.GetResponseStream(); 17 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); 18 string retString = myStreamReader.ReadToEnd(); 19 myStreamReader.Close(); 20 myResponseStream.Close(); 21 }
httpPost 方式发送请求 带参数
1 /// <summary> 2 /// 带有参数的post请求
/// UserID、TransFlow 参数名 3 /// </summary> 4 public void HttpPostParam() 5 { string Url = "请求地址"; 6 HttpWebRequest request = WebRequest.CreateHttp(Url); 7 request.Method = "POST"; 8 request.ContentType = "application/x-www-form-urlencoded"; 9 string param = "UserID=2098&TransFlow=2"; 10 byte[] by; 11 by = System.Text.Encoding.UTF8.GetBytes(param); 12 request.ContentLength = by.Length; 13 Stream myRequestStream = request.GetRequestStream(); 14 StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312")); 15 myRequestStream.Write(by, 0, by.Length); 16 myStreamWriter.Close(); 17 myRequestStream.Close(); 18 19 20 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 21 Stream myResponseStream = response.GetResponseStream(); 22 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); 23 string retString = myStreamReader.ReadToEnd(); 24 myStreamReader.Close(); 25 myResponseStream.Close(); 26 }
httpGet 方式发送请求
1 /// <summary> 2 /// Get方式 3 /// </summary> 4 public void HttpGet() 5 { 6 string url = "请求地址?ID=2"; 7 HttpWebRequest request = WebRequest.CreateHttp(url); 8 request.Method = "Get"; 9 request.ContentType = "application/x-www-form-urlencoded"; 10 11 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 12 Stream read = response.GetResponseStream(); 13 StreamReader sm = new StreamReader(read, System.Text.Encoding.UTF8); 14 string readString = sm.ReadToEnd(); 15 16 }