asp.net 后台 get,post请求

时间:2020-12-26 06:49:36

//Post请求
public static string Post(string url,string obj=null)
{
string param = (obj);//参数
byte[] bs = Encoding.Default.GetBytes(param);

//创建一个新的HttpWebRequest对象。
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);

// 将方法属性设置为“POST”以将数据发布到URI。
req.Method = "POST";

//设置contentType属性。
req.ContentType = "application/json";

req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);

reqStream.Close();
HttpWebResponse response2 = (HttpWebResponse)req.GetResponse();
StreamReader sr2=new StreamReader(response2.GetResponseStream(), Encoding.UTF8);
string text2 = sr2.ReadToEnd();
return text2;
}

}

//Get请求
public static string Get(string func, string strParam = null)
{
string result = "";
StringBuilder realUrl = new StringBuilder();
realUrl.Append(func).Append("?");
StringBuilder param = new StringBuilder();

if (strParam != null)
{
if (param.Length > 0)
{
param.Append("&");
}
param.Append(strParam);
}
realUrl.Append(param.ToString());
WebRequest req = WebRequest.Create(realUrl.ToString());
req.ContentType = "text/html; charset=GBK";

WebResponse res = req.GetResponse();
Stream stream = res.GetResponseStream();

using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("gb2312")))
{
result = reader.ReadToEnd();
}
return result;
}

//Get请求
public static string Get(string func)
{
     using (System.IO.StreamReader reader = new System.IO.StreamReader(WebRequest.Create(func).GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")))
     {
         return reader.ReadToEnd();
    }
}