/// <summary>
/// 通过web api获取数据的方法
/// </summary>
/// <param name="url">api的url</param>
/// <param name="method">请求类型,默认是get</param>
/// <param name="postData">post请求所携带的数据</param>
/// <returns></returns>
public static string RequestData(string url, string method = "Get", string postData = null)
{
try
{
method = method.ToUpper();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//設置安全性通信協議 通信協議是https時如果沒有下面的設置會報錯誤:HttpWebRequest底層連線已關閉:傳送時發生意外錯誤
ServicePointManager.SecurityProtocol =
SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls |
SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; //版本
//方式
request.Method = method;
request.ContentType = "application/json";
Stream myResponseStream = null;
//POST方式處理
if (method == "POST")
{
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
//request.MaximumAutomaticRedirections = 1;
//request.AllowAutoRedirect = true;
myResponseStream = request.GetRequestStream();
myResponseStream.Write(byteArray, 0, byteArray.Length);
myResponseStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
return retString;
}
catch (Exception ex)
{
//拋出異常
throw ex;
}
}
已封装好的方法--用来通过调用WebApi获取数据
最新推荐文章于 2023-05-19 15:40:06 发布
该代码段展示了如何通过C#的HttpWebRequest类实现GET和POST请求,从WebAPI获取数据。它设置安全协议以支持多种TLS版本,并处理POST请求的数据写入。此方法对于进行HTTP请求交互非常有用。
摘要由CSDN通过智能技术生成