1.Get方式传数据
public static string MyHttpGet(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
2.Post方式传数据
public static string MyHttpPost(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "multipart/form-data;boundary=----------" + DateTime.Now.Ticks.ToString("x");//表头的格式必须要写,否则请求响应的页面得不到要传递的值
byte[] SomeBytes = Encoding.ASCII.GetBytes(postDataStr);//传递的值
request.ContentLength = SomeBytes.Length;
Stream newStream = request.GetRequestStream();//把传递的值写到流中
newStream.Write(SomeBytes, 0, SomeBytes.Length);
newStream.Close();//必须要关闭请求
HttpWebResponse httpWebResponse = null;
httpWebResponse = (HttpWebResponse)request.GetResponse();
Stream s = httpWebResponse.GetResponseStream();
StreamReader reader = new StreamReader(s, Encoding.GetEncoding("utf-8"));
string respText = reader.ReadToEnd();
s.Close();
return respText;
}