C# Web Api HTTP Get (result as a string)

为了方便调用,通常封装成一个通用的函数,如下:
/// <summary>
        /// Get Http as string result
        /// </summary>
        /// <param name="url">Request Url.</param>
        /// <param name="strAccessToken">Access Token.</param>
        public WebApiResult HttpGetAsString(string url, string strAccessToken)
        {
            string result = "";
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Headers.Add("Authorization", "Bearer " + strAccessToken);
                request.Method = "GET";
                request.AllowAutoRedirect = true;
                request.Timeout = 20 * 1000;
                request.ContentType = "application/json";

                var response = (HttpWebResponse)request.GetResponse();
                var rspStream = response.GetResponseStream();
                using (var reader = new StreamReader(rspStream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                    rspStream.Close();
                }
                response.Close();
            }
            catch (Exception ex)
            {
                return new WebApiResult { IsSuccess = false, Data = ex.Message };
            }
            return new WebApiResult { IsSuccess = true, Data = result };
        }
    }

    public class WebApiResult
    {
        public bool IsSuccess { get; set; }

        public string Data { get; set; }
    }

当IsSuccess为true时,Data为返回的调用结果的字符串(Json),可以反序列化为对象。

当IsSuccess为false时,Data为异常message。

posted @ 2022-08-30 14:09  SilverFox8588  阅读(80)  评论(0编辑  收藏  举报