C# WPF从RIOT API获取数据(RIOT代表作品《英雄联盟》)

微信公众号:Dotnet9,网站:Dotnet9,问题或建议:请网站留言
如果对您有所帮助:欢迎赞赏

C# WPF从RIOT API获取数据(RIOT代表作品《英雄联盟》)

阅读导航

  1. 本文背景
  2. 代码实现
  3. 本文参考

1. 本文背景

RIOT(拳头)是一家美国网游开发商,成立于2006年,代表作品《英雄联盟》。

本文重点要讲解两个知识点:

  1. C# 使用 HttpClient 访问 RIOT 提供的 API 接口,获取召唤者概况信息;
  2. C# WPF界面展示召唤者信息搜索、概况信息两个界面。

2. 代码实现

站长使用 .Net CORE 3.1 创建名为 “LoLGoal” 的WPF解决方案,并添加3个Nuget包,配置如下:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="MaterialDesignColors" version="1.1.1" targetFramework="net45" />
  <package id="MaterialDesignThemes" version="2.5.0.1205" targetFramework="net45" />
  <package id="Newtonsoft.Json" version="12.0.1" targetFramework="net45" />
</packages>

界面使用的MD控件,本站曾有介绍:介绍

本文只简单说明部分代码,整体解决方案目录结构如下,源码文末会给出:

2.1 引入MD控件样式

文件【App.xaml】

<Application x:Class="LoLGoal.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="View/MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.Purple.xaml" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Blue.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

2.2 召唤者概况搜索界面

文件【MainWindow.xaml】代码,界面布局简单,给人的感觉整体简洁大方:

<Window x:Class="LoLGoal.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d" Height="600" Width="400" WindowStartupLocation="CenterScreen"
        MouseLeftButtonDown="Window_MouseLeftButtonDown"
        ResizeMode="NoResize" WindowStyle="None" Background="#FF410A66">
    <Grid>
        <StackPanel Margin="50">
            <Image Source="/Assets/logo2.png" Width="96" Height="96"/>
            <Border Background="White" Margin="10 20" CornerRadius="5">
                <StackPanel Margin="25">
                    <ComboBox Margin="15" Style="{StaticResource MaterialDesignFloatingHintComboBox}" materialDesign:HintAssist.Hint="地区" Text="{Binding Region}">
                        <ComboBoxItem Content="RU"/>
                        <ComboBoxItem Content="KR"/>
                        <ComboBoxItem Content="BR1"/>
                        <ComboBoxItem Content="OC1"/>
                        <ComboBoxItem Content="JP1"/>
                        <ComboBoxItem Content="NA1"/>
                        <ComboBoxItem Content="EUN1"/>
                        <ComboBoxItem Content="EUW1"/>
                        <ComboBoxItem Content="TR1"/>
                        <ComboBoxItem Content="LA1"/>
                        <ComboBoxItem Content="LA2"/>
                    </ComboBox>
                    <TextBox Text="{Binding SummonerName}" Margin="15" Style="{StaticResource MaterialDesignFloatingHintTextBox}" materialDesign:HintAssist.Hint="召唤者"/>
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                        <Button Margin="15 50" Content="取消"/>
                        <Button x:Name="ButtonSignUp" Margin="15 50" Content="搜索" Click="ButtonSignUp_Click"/>
                    </StackPanel>
                </StackPanel>
            </Border>
        </StackPanel>
    </Grid>
</Window>

召唤者概况搜索界面

2.3 召唤者概况信息展示界面

文件【WindowProfile.xaml】,布局代码也不多,清爽:

<Window x:Class="LoLGoal.View.WindowProfile"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d" Height="600" Width="400"
        WindowStartupLocation="CenterScreen" ResizeMode="NoResize"
        WindowStyle="None" Background="#FF410A66">
    <Grid>
        <Border Background="White" Margin="20 100 20 20" CornerRadius="15">
            <StackPanel VerticalAlignment="Top" HorizontalAlignment="Stretch">
                <Border Width="100" Height="100" Margin="20 20 0 10" BorderBrush="Gray" HorizontalAlignment="Left" BorderThickness="1" CornerRadius="15">
                    <Border.Background>
                        <ImageBrush ImageSource="{Binding Path=Icon}"/>
                    </Border.Background>
                </Border>
                <TextBlock Margin="20 15" FontSize="30" Text="{Binding Path=SummonerName}" Foreground="DarkGray"/>
                <StackPanel Orientation="Horizontal" Margin="20 0">
                    <StackPanel Margin="5">
                        <TextBlock Text="胜" FontSize="15" FontWeight="Bold" Foreground="Green"/>
                        <TextBlock Text="{Binding Path=Wins}" FontSize="18" Foreground="Gray" HorizontalAlignment="Center"/>
                    </StackPanel>
                    <StackPanel Margin="5">
                        <TextBlock Text="输" FontSize="15" FontWeight="Bold" Foreground="DarkRed"/>
                        <TextBlock Text="{Binding Path=Losses}" FontSize="18" Foreground="Gray" HorizontalAlignment="Center"/>
                    </StackPanel>
                </StackPanel>
                <StackPanel Margin="30 20">
                    <TextBlock Text="水平" FontSize="15" Foreground="LightGray"/>
                    <TextBlock Text="{Binding Path=Level}" HorizontalAlignment="Center" FontSize="80" Foreground="Gray"/>
                </StackPanel>
                <Grid Margin="20 10">
                    <Button x:Name="ButtonSearch" HorizontalAlignment="Left" Style="{StaticResource MaterialDesignFlatButton}" Width="100" Click="ButtonSearch_Click">
                        <materialDesign:PackIcon Kind="Search" Width="24" Height="24"/>
                    </Button>
                    <Button HorizontalAlignment="Right" Width="100" Content="登录"/>
                </Grid>
            </StackPanel>
        </Border>
        <StackPanel HorizontalAlignment="Right" Margin="30 10">
            <Image Source="{Binding Path=Emblem}" Width="200" Height="200">
                <Image.Effect>
                    <DropShadowEffect BlurRadius="40" ShadowDepth="1"/>
                </Image.Effect>
            </Image>
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="5">
                <TextBlock FontSize="18" Foreground="Gray" Text="{Binding Path=Tier}" Margin="5" VerticalAlignment="Center"/>
                <TextBlock FontSize="20" Foreground="Gray" Text="{Binding Path=Rank}" Margin="5"/>
            </StackPanel>
        </StackPanel>
    </Grid>
</Window>

概况信息展示界面

2.4 简单的API接口调用封装

直接上代码看,Key.txt是存储的RIOT开发者Key:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace LoLGoal.API
{
    public class Api
    {
        private string Key { get; set; }
        private string Region { get; set; }

        public Api(string region)
        {
            Region = region;
            Key = GetKey("API/Key.txt");
        }

        protected HttpResponseMessage GET(string URL)
        {
            using (HttpClient client = new HttpClient())
            {
                var result = client.GetAsync(URL);
                result.Wait();

                return result.Result;
            }
        }

        protected string GetURI(string path)
        {
            return "https://" + Region + ".api.riotgames.com/lol/" + path + "?api_key=" + Key;
        }

        public string GetKey(string path)
        {
            StreamReader sr = new StreamReader(path);
            return sr.ReadToEnd();
        }
    }
}

2.5 其他代码

查看源码:get_profile_data

2.6 以下是站长方便演示、截图,修改的部分文件

可参考源码对比:

文件【API/League_V4.cs】

using LoLGoal.Model;
using System;
using System.Collections.Generic;

namespace LoLGoal.API
{
    public class League_V4 : Api
    {
        public League_V4(string region) : base(region)
        {
        }

        public List<PositionDTO> GetPositions(string summonerId)
        {
            //1、这是正常的API访问
            //string path = "league/v4/positions/by-summoner/" + summonerId;

            //var response = GET(GetURI(path));
            //string content = response.Content.ReadAsStringAsync().Result;

            //if (response.StatusCode == System.Net.HttpStatusCode.OK)
            //{
            //    return JsonConvert.DeserializeObject<List<PositionDTO>>(content);
            //}
            //else
            //{
            //    return null;
            //}

            //2、这是模拟数据,正常访问LOL服务器,需要注册Key
            string[] tiers = { "Bronze", "Challenger", "Diamond", "Gold", "Grandmaster", "Iron", "Master", "Platinum", "Silver" };
            var rd = new Random(DateTime.Now.Millisecond);
            var lst = new List<PositionDTO>();
            for (int i = 0; i < rd.Next(5, 20); i++)
            {
                lst.Add(new PositionDTO
                {
                    Tier = tiers[rd.Next(0, tiers.Length)],
                    Rank = "IV",
                    Wins = rd.Next(2, 100),
                    Losses = rd.Next(2, 100),
                    QueueType = "RANKED_SOLO_5x5"
                });
            }
            return lst;
        }
    }
}

文件【API/Summoner_V4.cs】

using LoLGoal.Model;
using System;

namespace LoLGoal.API
{
    public class Summoner_V4 : Api
    {
        public Summoner_V4(string region) : base(region)
        {
        }

        public SummonerDTO GetSummonerByName(string SummonerName)
        {
            //1、这是正常的API访问
            //string path = "summoner/v4/summoners/by-name/" + SummonerName;

            //var response = GET(GetURI(path));
            //string content = response.Content.ReadAsStringAsync().Result;

            //if(response.StatusCode == System.Net.HttpStatusCode.OK)
            //{
            //    return JsonConvert.DeserializeObject<SummonerDTO>(content);
            //}
            //else
            //{
            //    return null;
            //}

            //2、这是模拟数据,正常访问LOL服务器,需要注册Key
            return new SummonerDTO
            {
                ProfileIconId = DateTime.Now.Second,
                Name = SummonerName,
                SummonerLevel = new Random(DateTime.Now.Millisecond).Next(50, 200),
                Id = DateTime.Now.Second.ToString()
            };
        }
    }
}

3.参考

  1. 视频一:C# WPF Design UI - #1 - Login,配套源码:LoLGoal
  2. 视频二:C# WPF Design UI - #2 (1/2) - REST API Access,配套源码:get_summoner_data
  3. 视频三:C# WPF Design UI - #2 (2/2) - REST API Access,配套源码:get_summoner_data
  4. 视频四:C# WPF Design UI - #3 - Profile,配套源码:summoner_profile
  5. 视频五:C# WPF Design UI - #4 (1/2) - Get Data From RIOT API,配套源码:get_profile_data
  6. 视频六:C# WPF Design UI - #4 (2/2)- Get Data From RIOT API,配套源码:get_profile_data

最终源码:本文代码几乎和源码一致(第五和第六个视频配套Github源码 【get_profile_data】),站长未注册RIOT开发者Key,所以代码中采用模拟返回数据的方式,只展示了界面效果,并将部分英文改为中文,便于向大家展示此工程。

点击下载源码:get_profile_data

除非注明,文章均由 Dotnet9 整理发布,欢迎转载。

转载请注明本文地址:https://dotnet9.com/7026.html

欢迎扫描下方二维码关注 Dotnet9 的微信公众号,本站会及时推送最新技术文章

原文地址:https://www.cnblogs.com/Dotnet9-com/p/12187624.html

时间: 2024-07-30 02:49:23

C# WPF从RIOT API获取数据(RIOT代表作品《英雄联盟》)的相关文章

百度地图API获取数据

目前,大厂的服务范围越来越广,提供的数据信息也是比较全的,在生活服务,办公领域,人工智能等方面都全面覆盖,相对来说,他们的用户基数大,通过用户获取的信息也是巨大的.除了百度提供api,国内提供免费API获取数据的还有很多,包括新浪.豆瓣电影.饿了么.阿里.腾讯等今天使用百度地图API来请求我们想要的数据. 第一步.注册百度开发者账号 注册成功后就可以获取到应用服务AK也就是API秘钥,这个是最重要的,应用名称可以随便取,如果是普通用户一天只有2000调用限额,认证用户一天有10万次调用限额 在百

使用api获取数据————小程序

使用api获取数据----小程序 onLoad: function (options) { //打开页面即执行. let that = this; wx.request({ //建立链接 url: 'http://web.juhe.cn:8080/constellation/getAll', //api获取的地址 data: { consName: "巨蟹座", //给api传输的数据 type: "today", //给api传输的数据 key: app.glob

C#/.NET使用HttpWebRequest、SqlBulkCopy从API获取数据批量插入DB

小弟新手程序员一枚,代码技术和文章水平均不才.所写文章均为对自己所写所学代码的简单记录,可能对于老手程序员营养价值不高,望莫见怪. 我工作上有个需求:从某处API接口上获取数据(大约1W条而已)并插入到数据库中. 楼主刚毕业菜鸟,没做过批量插入操作.借助baidu搜索得知SqlBulkCopy可以实现.SqlBulkCopy相关的原理,我现在还没了解就不摆弄了,以后补上! (不要问为什么不用google,公司内网就连msdn.microsoft.com都不给上!另外我公司是开发C#/.NET的,

通过新浪微博API获取数据

要获取新浪微博的数据,可以通过他们提供的API,地址:http://open.weibo.com/wiki/API文档_V2. 获取数据的方法如下: <?php function getWeiboData() { $count = 15; // 参数source后面输入你的授权号 $url = "https://api.weibo.com/2/statuses/home_timeline.json?source=123456789&count=".$count."

百度统计api获取数据(前端调用)

需求场景 想要了解每天多少人访问了网站,多少个新增用户,地域分布,点击了哪些页面,停留了多久,等等... 国内用的最多的就是百度统计吧,傻瓜式的注册然后插一段代码到项目里就行了. 最近也在自己的博客里使用了百度统计,但是当想要获取这些数据时,看到官方文档,简直想骂人.网上也不是没有代码示例,但清一色的都是java代码,而官网给出的demo也是php,这是要逼死前端吗? 来吧,直接上代码: 1.  获取站点    https://api.baidu.com/json/tongji/v1/Repor

PHP通过Zabbix API获取服务器监控信息

开源监控系统Zabbix提供了丰富的API,供第三方系统调用. 基本步骤如下: 1.获取合法认证:连接对应Zabbix URL,并提供用户名和密码,HTTP方法为"POST",HTTP头部类型为"application/json" 1 public function zabbixJsonRequest($uri, $data) { 2 try{$json_data = json_encode($data); 3 $c = curl_init(); 4 curl_se

StormUI 无法获取数据

名词解决 SPNEGO(SPNEGO: Simple and Protected GSS-API Negotiation)是微软提供的一种使用GSS-API认证机制的安全协议,用于使Webserver共享Windows Credentials,它扩展了Kerberos(一种网络认证协议). 原因 当使用Kerberos进行认证时,通过Ambari-server访问某一个集群应用的HTTP协议API的时候,需要把Ambari WEB端已经通过GSS-API认证的Kerberos principal

Web Api 获取post json数据

这周在做一个webApi的模拟后台.遇到些问题.和大家分享一下,以前没有搞过webapi.所以不是太懂. 当我发post请求的json数据过来的时候,如果我用context.Request .Form去收的时候会发现,一小半的json数据跑到了Key里面,其他数据在form[0]中,很奇怪.后来恍然大悟我发送的又不是表单干嘛用表单去接收,然后去用HttpContext.Current.Request.InputStream.Read(byts, 0, byts.Length);直接读取流然后再转

Html网页使用jQuery传递参数并获取Web API的数据

昨天Insus.NET有开始学习Web API,<ASP.NET MVC的Web Api的实练>http://www.cnblogs.com/insus/p/4334316.html .其中演练中有提及到出现异常并解决,也有举例实现了在html静态网页使用jQuery来去读Web API的数据. 本篇想实现在html网页使用jQuery实现向Web API传递参数并获取数据. 在API创建一个方法public IEnumerable<Order> GetOrderByOrderNu