C#中Get和Post请求的同步及异步方法

2021-02-12 13:19

阅读:305

标签:ati   http   exception   ssi   public   repo   http post   nbsp   streambuf   

在C#中发起Http请求一般使用HttpWebRequest这个类,下文将使用这个HttpWebRequest对象来对Get和Post的同步及异步请求进行封装:

1. 新建HttpRequestHelper类:

    public static class  HttpRequestHelper
    {
        /// 
        /// Http Get Request
        /// 
        /// 
        /// 
        public static string HttpGetRequest(string url)
        {
            string strGetResponse = string.Empty;
            try
            {
                var getRequest = CreateHttpRequest(url, "GET");
                var getResponse = getRequest.GetResponse() as HttpWebResponse;
                strGetResponse = GetHttpResponse(getResponse, "GET");
            }
            catch (Exception ex)
            {
                strGetResponse = ex.Message;
            }
            return strGetResponse;
        }

        /// 
        /// Http Get Request Async
        /// 
        /// 
        public static async void HttpGetRequestAsync(string url)
        {
            string strGetResponse = string.Empty;
            try
            {
                var getRequest = CreateHttpRequest(url, "GET");
                var getResponse = await getRequest.GetResponseAsync() as HttpWebResponse;
                strGetResponse = GetHttpResponse(getResponse, "GET");
            }
            catch (Exception ex)
            {
                strGetResponse = ex.Message;
            }
            return strGetResponse;
            Console.WriteLine("reslut:" + strGetResponse);
        }

        /// 
        /// Http Post Request
        /// 
        /// 
        /// 
        /// 
        public static string HttpPostRequest(string url, string postJsonData)
        {
            string strPostReponse = string.Empty;
            try
            {
                var postRequest = CreateHttpRequest(url, "POST", postJsonData);
                var postResponse = postRequest.GetResponse() as HttpWebResponse;
                strPostReponse = GetHttpResponse(postResponse, "POST");
            }
            catch (Exception ex)
            {
                strPostReponse = ex.Message;
            }
            return strPostReponse;
        }

        /// 
        /// Http Post Request Async
        /// 
        /// 
        /// 
        public static async void HttpPostRequestAsync(string url, string postData)
        {
            string strPostReponse = string.Empty;
            try
            {
                var postRequest = CreateHttpRequest(url, "POST", postData);
                var postResponse = await postRequest.GetResponseAsync() as HttpWebResponse;
                strPostReponse = GetHttpResponse(postResponse, "POST");
            }
            catch (Exception ex)
            {
                strPostReponse = ex.Message;
            }
            if (strPostReponse != "true")
            {
                Console.WriteLine("--> reslut : " + strPostReponse);
                Console.WriteLine(postData);
            }
        }

        private static HttpWebRequest CreateHttpRequest(string url, string requestType, params object[] strJson)
        {
            HttpWebRequest request = null;
            const string get = "GET";
            const string post = "POST";
            if (string.Equals(requestType, get, StringComparison.OrdinalIgnoreCase))
            {
                request = CreateGetHttpWebRequest(url);
            }
            if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
            {
                request = CreatePostHttpWebRequest(url, strJson[0].ToString());
            }
            return request;
        }

        private static HttpWebRequest CreateGetHttpWebRequest(string url)
        {
            var getRequest = HttpWebRequest.Create(url) as HttpWebRequest;
            getRequest.Method = "GET";
            getRequest.Timeout = 5000;
            getRequest.ContentType = "text/html;charset=UTF-8";
            getRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            return getRequest;
        }

        private static HttpWebRequest CreatePostHttpWebRequest(string url, string postData)
        {
            var postRequest = HttpWebRequest.Create(url) as HttpWebRequest;
            postRequest.KeepAlive = false;
            postRequest.Timeout = 5000;
            postRequest.Method = "POST";
            postRequest.ContentType = "application/x-www-form-urlencoded";
            postRequest.ContentLength = postData.Length;
            postRequest.AllowWriteStreamBuffering = false;
            StreamWriter writer = new StreamWriter(postRequest.GetRequestStream(), Encoding.ASCII);
            writer.Write(postData);
            writer.Flush();
            return postRequest;
        }

        private static string GetHttpResponse(HttpWebResponse response, string requestType)
        {
            var responseResult = "";
            const string post = "POST";
            string encoding = "UTF-8";
            if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
            {
                encoding = response.ContentEncoding;
                if (encoding == null || encoding.Length 1)
                {
                    encoding = "UTF-8";
                }
            }
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)))
            {
                responseResult = reader.ReadToEnd();
            }
            return responseResult;
        }

        private static string GetHttpResponseAsync(HttpWebResponse response, string requestType)
        {
            var responseResult = "";
            const string post = "POST";
            string encoding = "UTF-8";
            if (string.Equals(requestType, post, StringComparison.OrdinalIgnoreCase))
            {
                encoding = response.ContentEncoding;
                if (encoding == null || encoding.Length 1)
                {
                    encoding = "UTF-8";
                }
            }
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)))
            {
                responseResult = reader.ReadToEnd();
            }
            return responseResult;
        }
    }

2. 使用

2.1  同步请求

     // Get
     var getUrl = "http://localhost:8888?";
     HttpRequestHelper.HttpGetRequest(getUrl);

     // Post
     var postUrl = "http://localhost:8888";
     var postObj = new
     {
          username = "DamonZhu",
          password = "12345678"
     };
     var postData = JsonConvert.SerializeObject(postObj);
     HttpRequestHelper.HttpPostRequest(postUrl, postData);

2.2 异步请求

    // Get Async
    var getUrl = "http://localhost:8888?";
    HttpRequestHelper.HttpGetRequest(getUrl);

    // Post Async
    var postUrl = "http://localhost:8888";
    var postObj = new
    {
        username = "DamonZhu",
        password = "12345678"
    };
    var postData = JsonConvert.SerializeObject(postObj);
    HttpRequestHelper.HttpPostRequest(postUrl, postData);

 

 

C#中Get和Post请求的同步及异步方法

标签:ati   http   exception   ssi   public   repo   http post   nbsp   streambuf   

原文地址:https://www.cnblogs.com/DamonCoding/p/8475466.html


评论


亲,登录后才可以留言!