1. 程式人生 > >C# 呼叫http和https請求rest介面通用操作類

C# 呼叫http和https請求rest介面通用操作類

之前在做C#呼叫Restful介面的時候,因為時間比較匆忙,一直沒有把這個類好好整理一下。最近一方面對於ContentType的整理感覺很不方便,另一方面對於Restful介面http和https呼叫使用不同的類感覺很不方便,發現呼叫http和https只要用一句話就可以解決了。於是,整理一個通用類,記錄下來,方便以後使用。

感謝網上各路大神提供的資料。

程式碼如下:

using System;
using System.IO;
using System.Net;
using System.Text;
// 新增https
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
// end新增https


namespace NT_MiddleDataService.ADO
{
    public enum HttpVerbNew
    {
        GET,            //method  常用的就這幾樣,可以新增其他的   get:獲取    post:修改    put:寫入    delete:刪除
        POST,
        PUT,
        DELETE
    }


    public class ContentType//根據Postman整理,可以新增
    { 
        public string Text = "text/plain";
        public string JSON = "application/json";
        public string Javascript = "application/javascript";
        public string XML = "application/xml";
        public string TextXML = "text/xml";
        public string HTML = "text/html";
    }


    public class RestApiClient
    {
        public string EndPoint { get; set; }    //請求的url地址  
        public HttpVerbNew Method { get; set; }    //請求的方法
        public string ContentType { get; set; } //格式型別
        public string PostData { get; set; }    //傳送的資料


        public RestApiClient()
        {
            EndPoint = "";
            Method = HttpVerbNew.GET;
            ContentType = "text/xml";
            PostData = "";
        }
        public RestApiClient(string endpoint, string contentType)
        {
            EndPoint = endpoint;
            Method = HttpVerbNew.GET;
            ContentType = contentType;
            PostData = "";
        }
        public RestApiClient(string endpoint, HttpVerbNew method, string contentType)
        {
            EndPoint = endpoint;
            Method = method;
            ContentType = contentType;
            PostData = "";
        }


        public RestApiClient(string endpoint, HttpVerbNew method, string contentType, string postData)
        {
            EndPoint = endpoint;
            Method = method;
            ContentType = contentType;
            PostData = postData;
        }


        // 新增https
        private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";


        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //總是接受     
        }
        // end新增https


        public string MakeRequest()
        {
            return MakeRequest("");
        }


        public string MakeRequest(string parameters)
        {
            var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);


            // 新增https
            if (EndPoint.Substring(0, 8) == "https://")
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            // end新增https


            request.Method = Method.ToString();
            request.ContentLength = 0;
            request.ContentType = ContentType;


            if (!string.IsNullOrEmpty(PostData) && Method == HttpVerbNew.POST)//如果傳送的資料不為空,並且方法是post
            {
                var encoding = new UTF8Encoding();
                var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);//編碼方式按自己需求進行更改,我在專案中使用的是UTF-8
                request.ContentLength = bytes.Length;


                using (var writeStream = request.GetRequestStream())
                {
                    writeStream.Write(bytes, 0, bytes.Length);
                }
            }


            if (!string.IsNullOrEmpty(PostData) && Method == HttpVerbNew.PUT)//如果傳送的資料不為空,並且方法是put
            {
                var encoding = new UTF8Encoding();
                var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);//編碼方式按自己需求進行更改,我在專案中使用的是UTF-8
                request.ContentLength = bytes.Length;


                using (var writeStream = request.GetRequestStream())
                {
                    writeStream.Write(bytes, 0, bytes.Length);
                }
            }
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var responseValue = string.Empty;


                if (response.StatusCode != HttpStatusCode.OK)
                {
                    var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                    throw new ApplicationException(message);
                }


                // grab the response
                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                        using (var reader = new StreamReader(responseStream))
                        {
                            responseValue = reader.ReadToEnd();
                        }
                }


                return responseValue;
            }
        }


        public bool CheckUrl(string parameters)
        {
            bool bResult = true;


            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);
            myRequest.Method = Method.ToString();             //設定提交方式可以為"get","head"等
            myRequest.Timeout = 10000;              //設定網頁響應時間長度
            myRequest.AllowAutoRedirect = false;//是否允許自動重定向
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            bResult = (myResponse.StatusCode == HttpStatusCode.OK);//返回響應的狀態


            return bResult;
        }
    }
}

知行辦公,專業移動辦公平臺 https://zx.naton.cn/
【總監】十二春秋之,[email protected]Masterzelo[email protected]【運營】運維艄公,[email protected]【產品設計】流浪貓,[email protected]【體驗設計】兜兜,[email protected]iOS】淘碼小工,[email protected]iMcG33K[email protected]】人猿居士,[email protected];思路的頓悟,[email protected]

java】首席工程師MR_W[email protected]【測試】土鏡問道,[email protected]【資料】fox009521,[email protected]【安全】保密,你懂的。