asp.net 后台 get,post,patch请求
//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();
}
}
//PATCH请求
public static string HttpPatch(string getUrl,string requestData)
{
string strWXUrlAPI = System.Configuration.ConfigurationManager.AppSettings["WXUrlAPI"];
(string.IsNullOrEmpty(strWXUrlAPI)).Error("strWXUrlAPI地址不能为空");
HttpWebRequest httpWebRequest = null;
HttpWebResponse httpWebResponse = null;
try
{
httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(strWXUrlAPI+getUrl);
Func<string, byte[]> GetBytes = Encoding.UTF8.GetBytes;
byte[] buffer = GetBytes(requestData);
httpWebRequest.Referer = strWXUrlAPI + getUrl;
httpWebRequest.Accept = "application/json";
httpWebRequest.UserAgent = "firefox";
httpWebRequest.ContentType = "application/json";
httpWebRequest.ContentLength = buffer.Length;
httpWebRequest.Method = "PATCH";
httpWebRequest.SendChunked = true;
httpWebRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
string html = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
httpWebRequest.Abort();
httpWebResponse.Close();
return html;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
if (httpWebRequest != null) httpWebRequest.Abort();
if (httpWebResponse != null) httpWebResponse.Close();
return string.Empty;
}
}