GET/POST/Patch外部请求

/// <summary>
/// post请求
/// </summary>
/// <param name="postUrl">地址</param>
/// <param name="paramData">数据</param>
/// <param name="dataEncode">编码</param>
/// <returns></returns>
public static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
{
string ret = string.Empty;
try
{
byte[] byteArray = dataEncode.GetBytes(paramData); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";

webReq.ContentLength = byteArray.Length;
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
ret = sr.ReadToEnd();
sr.Close();
response.Close();
newStream.Close();
}
catch
{
throw;
}
return ret;
}

 

/// <summary> 
/// Get请求
/// </summary> /// <param name="url">url</param> 
/// <param name="encoding">返回内容编码方式,例如:Encoding.UTF8</param> 
public static String GetWebRequest(String url, Encoding encoding)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "GET";
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
StreamReader sr = new StreamReader(webResponse.GetResponseStream(), encoding);
return sr.ReadToEnd();
}

/// <summary>
/// Patch请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static string PatchResponse(string url, string postData)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "PATCH";


byte[] btBodys = Encoding.UTF8.GetBytes(postData);
httpWebRequest.ContentLength = btBodys.Length;
httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);


HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var streamReader = new StreamReader(httpWebResponse.GetResponseStream());
string responseContent = streamReader.ReadToEnd();


httpWebResponse.Close();
streamReader.Close();
httpWebRequest.Abort();
httpWebResponse.Close();


return responseContent;
}

 
作者:D调灬仔
出处:https://www.cnblogs.com/chj929555796/
您的推荐是我最大的动力,如果觉得这篇文章对你有帮助的话,请点个“推荐”哦,博主在此感谢!
原文地址:https://www.cnblogs.com/chj929555796/p/5569549.html