WPF随笔(五)--HttpClient访问第三方WebAPI接口

在WPF 项目中,有时会需要从第三方WebAPI接口获取数据。此时就需要用到位于System.Net.Http命名空间下的HttpClient类,同时为了提高代码复用率,将HttpClient访问API接口的方法做成通用类也是一个不错的想法。

设置WebAPI基地址

很多时候是需要访问同一站点的不同API接口,因此可以将站点基地址设为公共变量,最好是可以通过配置文件修改。

public static readonly string BaseUri = ConfigurationManager.AppSettings["ApiUri"];

GET方法

        #region GET请求--异步方法

        /// 
        /// GET请求--异步方法
        /// 
        /// 
        /// 方法
        /// 参数
        /// 
        public static async Task TryGetAsync(string action, Dictionary param)
        {
            using (HttpClient client = new HttpClient())
            {
                //基地址/域名
                client.BaseAddress = new Uri(BaseUri);
                //设定传输格式为json
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
                //client.DefaultRequestHeaders.Add("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");

                StringBuilder strUri = new StringBuilder();
                //方法
                strUri.AppendFormat("{0}?", action);
                //参数
                if (param.Count > 0)
                {
                    foreach (KeyValuePair pair in param)
                    {
                        strUri.AppendFormat("{0}={1}&&", pair.Key, pair.Value);
                    }
                    strUri.Remove(strUri.Length - 2, 2); //去掉'&&'
                }
                else
                {
                    strUri.Remove(strUri.Length - 1, 1); //去掉'?'
                }
                HttpResponseMessage response = await client.GetAsync(strUri.ToString());
                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsAsync();
                }
                return default(T);
            }
        }

        #endregion

        #region 无参数GET请求--异步方法

        /// 
        /// 无参数GET请求--异步方法
        /// 
        /// 
        /// 
        /// 
        public static async Task TryGetAsync(string action)
        {
            using (HttpClient client = new HttpClient())
            {
                //基地址/域名
                client.BaseAddress = new Uri(BaseUri);
                //设定传输格式为json
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.GetAsync(action);
                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsAsync();
                }
                return default(T);
            }
        }

        #endregion

POST方法

        #region POST请求--异步方法

        /// 
        /// POST请求--异步方法
        /// 
        /// 
        /// 方法
        /// 参数
        /// 
        public static async Task TryPostAsync(string action, object param)
        {
            using (HttpClient client = new HttpClient())
            {
                //基地址/域名
                client.BaseAddress = new Uri(BaseUri);
                //设定传输格式为json
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.PostAsync(action, param, new JsonMediaTypeFormatter());
                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsAsync();
                }
                return default(T);
            }
        }

        #endregion

文件上传

        #region 批量文件上传--含参数--异步方法

        /// 
        /// 批量文件上传--含参数--异步方法
        /// 
        /// 
        /// 
        /// 
        /// 
        public static async Task TryUploadAsync(string action, Dictionary filePaths,
            Dictionary param)
        {
            using (HttpClient client = new HttpClient())
            {
                using (var content = new MultipartFormDataContent())
                {
                    //基地址/域名
                    client.BaseAddress = new Uri(BaseUri);
                    foreach (var filePath in filePaths)
                    {
                        var fileContent = new ByteArrayContent(File.ReadAllBytes(filePath.Key));
                        fileContent.Headers.ContentDisposition =
                            new ContentDispositionHeaderValue("attachment")
                            {
                                FileName = filePath.Value
                            };
                        content.Add(fileContent);
                    }
                    foreach (var pair in param)
                    {
                        var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(pair.Value));
                        dataContent.Headers.ContentDisposition =
                            new ContentDispositionHeaderValue("attachment") {Name = pair.Key};
                        content.Add(dataContent);
                    }
                    HttpResponseMessage response = await client.PostAsync(action, content);
                    if (response.IsSuccessStatusCode)
                    {
                        return await response.Content.ReadAsStringAsync();
                    }
                    return await Task.FromResult("");
                }
            }
        }

        #endregion

你可能感兴趣的:(WPF,ASP.NET,WPF,HttpClient,WebAPI)