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

17 篇文章 3 订阅

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

设置WebAPI基地址

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

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

GET方法

        #region GET请求--异步方法

        /// <summary>
        /// GET请求--异步方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action">方法</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public static async Task<T> TryGetAsync<T>(string action, Dictionary<string, string> 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<string, string> 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<T>();
                }
                return default(T);
            }
        }

        #endregion

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

        /// <summary>
        /// 无参数GET请求--异步方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action"></param>
        /// <returns></returns>
        public static async Task<T> TryGetAsync<T>(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<T>();
                }
                return default(T);
            }
        }

        #endregion

POST方法

        #region POST请求--异步方法

        /// <summary>
        /// POST请求--异步方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action">方法</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public static async Task<T> TryPostAsync<T>(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<T>();
                }
                return default(T);
            }
        }

        #endregion

文件上传

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

        /// <summary>
        /// 批量文件上传--含参数--异步方法
        /// </summary>
        /// <param name="action"></param>
        /// <param name="filePaths"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public static async Task<string> TryUploadAsync(string action, Dictionary<string, string> filePaths,
            Dictionary<string, string> 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

  • 5
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
WPF(Windows Presentation Foundation)是一种用于创建Windows桌面应用程序的技术。而WebAPI是一种用于创建Web服务的框架。虽然WPF主要用于构建桌面应用程序,但我们可以使用WPF来生成WebAPI接口。 要生成WebAPI接口,我们可以按照以下步骤进行操作: 1. 创建WPF应用程序项目:在Visual Studio中创建一个新的WPF应用程序项目。 2. 添加WebAPI控制器类:在项目中添加一个控制器类,该类继承自System.Web.Http.ApiController,并实现所需的接口方法。在这些方法中,我们可以定义需要接收的HTTP请求和返回的数据。 3. 配置WebAPI路由:在Global.asax文件中配置WebAPI路由,以将HTTP请求路由到正确的控制器和方法中。 4. 编写业务逻辑:在控制器方法中,根据需求编写业务逻辑,可以连接数据库、调用其他服务等。 5. 运行应用程序:通过调试或发布应用程序,将其运行在本地的IIS或其他Web服务器上。 通过以上步骤,我们可以使用WPF生成WebAPI接口。此时,我们可以通过HTTP请求访问WPF应用程序中的接口,并获取返回的数据。 需要注意的是,尽管我们可以使用WPF来生成WebAPI接口,但这并不是WPF的主要用途。如果只需要创建WebAPI接口,建议使用专门的Web开发框架,如ASP.NET Core等。以上所述仅为一种可能的解决方案,具体实现方式可能因项目需求和框架版本而有所不同。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值