asp.net中WebRequest Post 及Get 数据实例

作者:袖梨 2022-06-25
sqlserver/42852.htm target=_blank >
代码如下 复制代码

public class WebRequestHelper
{
///


/// 以POST 形式请求数据
///

///
///
///
public static string PostData(string RequestPara,string Url)
{
WebRequest hr = HttpWebRequest.Create(Url);

byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(RequestPara);
hr.ContentType = "application/x-www-form-urlencoded";
hr.ContentLength = buf.Length;
hr.Method = "POST";

System.IO.Stream RequestStream = hr.GetRequestStream();
RequestStream.Write(buf, 0, buf.Length);
RequestStream.Close();

System.Net.WebResponse response = hr.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
string ReturnVal = reader.ReadToEnd();
reader.Close();
response.Close();

return ReturnVal;
}

///
/// 以GET 形式获取数据
///

///
///
///

public static string GetData(string RequestPara, string Url)
{
RequestPara=RequestPara.IndexOf('?')>-1?(RequestPara):("?"+RequestPara);

WebRequest hr = HttpWebRequest.Create(Url + RequestPara);

byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(RequestPara);
hr.Method = "GET";

System.Net.WebResponse response = hr.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
string ReturnVal = reader.ReadToEnd();
reader.Close();
response.Close();

return ReturnVal;
}
}

相关文章

精彩推荐