使用.NET的WebView2如何获取请求的响应内容,以微信直播的互动直播为例

背景

近几年直播行业快速发展,门槛也越来越低,越来越的人涌入直播大军。不得不说,直播不仅带来了更多的娱乐消遣,还提供了一个新型的就业方式。

说起直播的类型,有一个非常小众的娱乐直播,没有主播,全靠观众的弹幕互动。比如:直播修仙,观众发弹幕进入修仙,就可以看到自己的打坐小人,然后屏幕各种随机事件,送主播礼物可以获取各种道具。近期在微信刷视频号的时候,发现了好多类似的互动直播,有云蹦迪和各种互动游戏。.

使用.NET的WebView2如何获取请求的响应内容,以微信直播的互动直播为例

视频号直播截图

今天我们只聊技术,互动直播平台没有提供相关的 API 如何通过观众的评论来互动的?

实现原理

这里以微信视频号直播为例,介绍一种获取直播事件消息的方法,当然方法也适用于类似的其他平台。

视频号开启直播的时候在视频号的 Web 管理后台,会同时看到观众发送的评论和产生的其他互动。那么只需要通过开发一个浏览器插件就可以实现实时获取评论信息。这里我们 通过 WebView2 来获取请求评论的响应内容来实现。

实现步骤

首先创建一个 WPF 应用,添加 Microsoft.Web.WebView2 包,然后页面添加WebView2组件,首页直接为视频号管理后台。

<Grid>    <Wpf:WebView2 Source="https://channels.weixin.qq.com/platform/live/liveBuild" MinWidth="800" MinHeight="500" Name="webView"/></Grid>

WebView2初始化完成后绑定WebResourceResponseReceived事件。此事件可以获取到所有请求的内容,这里只需要获取/mmfinderassistant-bin/live/msg的链接请求即可,然后获取请求返回的内容。

public MainWindow(){    InitializeComponent();    webView.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted;}
private void WebView_CoreWebView2InitializationCompleted(object? sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e){    webView.CoreWebView2.WebResourceResponseReceived += CoreWebView2_WebResourceResponseReceivedAsync;}
private async void CoreWebView2_WebResourceResponseReceivedAsync(object? sender, CoreWebView2WebResourceResponseReceivedEventArgs e){    if (e.Request.Uri.EndsWith("/mmfinderassistant-bin/live/msg") && e.Response != null && e.Response.StatusCode==200)    {        Stream content = await e.Response.GetContentAsync();        string jsonText = new StreamReader(content).ReadToEnd();        var list = ToLiveMsg(jsonText);    }}

以下是内容的处理。

public List<LiveMsg> ToLiveMsg(string str) {    JsonNode jsonNode = JsonNode.Parse(str)!;    var res = new List<LiveMsg>();    var dataInfo = jsonNode["data"];    if (dataInfo is null) return res;    if (dataInfo["msgList"] is null) return res;
    foreach (var item in dataInfo["msgList"]!.AsArray())    {        var msg = JsonSerializer.Deserialize<LiveMsg>(item);        Debug.Print(msg.ToString());        res.Add(msg!);    }    return res;}
/// <summary>/// 直播互动消息内容/// </summary>/// <param name="nickname">昵称</param>/// <param name="headUrl">头像URL</param>/// <param name="content">消息内容</param>/// <param name="type">消息类型</param>/// <param name="username">用户ID</param>/// <param name="clientMsgId">消息ID</param>public record LiveMsg(string nickname,string headUrl,string content,int type,string username,string clientMsgId);

最后

这里介绍了评论的获取方式,点赞和礼物的消息,可以通过类似的方式审查请求获取到对应的内容。本文虽以互动直播为例,但主要为介绍如何使用.NET 的 WebView2 获取请求的响应内容。如果你对这种互动直播感兴趣可以通过 .NET 技术自己开发一个新的互动直播模式。