public string PostData(string url, string data)//url:要发送到网站的地址 data:传送需要的参数
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
// Send the data.
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] postdata = encoding.GetBytes(data);
newStream.Write(postdata, , data.Length);
newStream.Close();
// Get response
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.GetEncoding("gb2312"));
string content = reader.ReadToEnd();//得到结果 return content;
GET方法:
Uri uri = new Uri(url + "?" + postData);
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
request.Timeout = ;
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(responseStream, System.Text.Encoding.UTF8);
string retext = readStream.ReadToEnd().ToString();
readStream.Close();
return retext; }