已封装好的方法--用来通过调用WebApi获取数据

该代码段展示了如何通过C#的HttpWebRequest类实现GET和POST请求,从WebAPI获取数据。它设置安全协议以支持多种TLS版本,并处理POST请求的数据写入。此方法对于进行HTTP请求交互非常有用。
摘要由CSDN通过智能技术生成
/// <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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值