标签:
1 public string PostData(string url, string data)//url:要发送到网站的地址 data:传送需要的参数 2 { 3 HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); 4 myRequest.Method = "POST"; 5 myRequest.ContentType = "application/x-www-form-urlencoded"; 6 myRequest.ContentLength = data.Length; 7 Stream newStream = myRequest.GetRequestStream(); 8 // Send the data. 9 ASCIIEncoding encoding = new ASCIIEncoding(); 10 byte[] postdata = encoding.GetBytes(data); 11 newStream.Write(postdata, 0, data.Length); 12 newStream.Close(); 13 // Get response 14 HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); 15 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.GetEncoding("gb2312")); 16 string content = reader.ReadToEnd();//得到结果 17 18 return content;
GET方法:
1 Uri uri = new Uri(url + "?" + postData); 2 System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri); 3 request.Method = "GET"; 4 request.ContentType = "application/x-www-form-urlencoded"; 5 request.AllowAutoRedirect = false; 6 request.Timeout = 5000; 7 System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); 8 Stream responseStream = response.GetResponseStream(); 9 StreamReader readStream = new StreamReader(responseStream, System.Text.Encoding.UTF8); 10 string retext = readStream.ReadToEnd().ToString(); 11 readStream.Close(); 12 return retext; 13 14 }
标签:
原文地址:http://www.cnblogs.com/a-dou/p/5755226.html