用C#发送post请求,实现更改B站直播间标题[简单随笔]

2023-07-12,,

第一次发这样的网络数据包。记录一下。

API参考 https://github.com/SocialSisterYi/bilibili-API-collect/blob/master/live/manage.md

做了很多尝试才成功,遇到最大的困难是总是报告未登录,拯救我的是打开浏览器观察数据包格式。如图所示

筛选以定位对应请求,观察请求的具体格式,发现表单内容有两项csrf相关的键值对,我之前请求时只发了其中一个。此外也通过此方法确定了post请求的键值对是怎样打包和编码的。

如果编码方式错误,或输入随机字符,反馈信息一般是csrf验证错误。

下面列代码。

工具类。提供Post功能、cookie转化为字典功能。其中Post用了新版.Net库提供的HttpClient。

值得注意的是,数据的键值对以字典(好吧实际上用的是一个键值对数组)方式传入,编码时先对键和值分别编码,然后直接用"="和"&"拼接。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Net.Http.Headers; namespace TestFor_BLiveAPI
{
public static class TheUtil
{
public static string Post(string url, string cookie, List<KeyValuePair<string, string>> dataList)
{
HttpClient httpClient = new HttpClient(); var encData = "";
bool isFirstDataItem = true;
foreach (var dataItem in dataList)
{
string addi = isFirstDataItem ? "" : "&";
isFirstDataItem = false;
string curLine = WebUtility.UrlEncode(dataItem.Key) + "=" + WebUtility.UrlEncode(dataItem.Value);
encData += addi + curLine;
}
Console.WriteLine(encData);
byte[] btData = Encoding.UTF8.GetBytes(encData);
var ctns = new ByteArrayContent(btData);
ctns.Headers.ContentLength = btData.Length;
ctns.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded; charset=UTF-8");
ctns.Headers.Add("cookie", cookie);
var tsk = httpClient.PostAsync(url, ctns);
tsk.Wait();
using (var stm = new StreamReader(tsk.Result.Content.ReadAsStream(), Encoding.UTF8))
{
return stm.ReadToEnd();
}
} public static Dictionary<string, string> CookieToDict(string cookie)
{
Dictionary<string, string> resDict = new Dictionary<string, string>();
var items = cookie.Split(';');
for (int i = 0; i < items.Length; i++)
{
var curItem = items[i].Trim();
var lr = curItem.Split("=");
resDict[lr[0].Trim()] = lr[1].Trim();
}
return resDict;
}
}
}

实际运行代码

using TestFor_BLiveAPI;

string cookie = "————从浏览器中拷贝出的一长串文本,它是你的cookie————";
//把cookie放进字典里,方便提取需要的信息
var cookieDict = TheUtil.CookieToDict(cookie); char[] titleRanRes = new char[] {
'喵','汪','咪','咕','嘎','咩','噗','啊','呜','嘤','呼',
}; Random r = new Random(); string ranTitle = "";
for (int i = 0; i < 5; i++)
{
//拼接一个随机直播间标题,方便确认是否改成功
ranTitle += titleRanRes[r.Next(titleRanRes.Length)];
}
string csrfVal = cookieDict["bili_jct"]; Console.WriteLine("尝试变更直播间标题=" + ranTitle); var res = TheUtil.Post("https://api.live.bilibili.com/room/v1/Room/update", cookie,
new List<KeyValuePair<string, string>>() {
new KeyValuePair<string, string>("room_id","669896"),
new KeyValuePair<string, string>("title",ranTitle),
new KeyValuePair<string, string>("csrf_token",csrfVal),
new KeyValuePair<string, string>("csrf",csrfVal),
}); Console.WriteLine(res); Console.WriteLine("以上。");
Console.ReadLine();

用C#发送post请求,实现更改B站直播间标题[简单随笔]的相关教程结束。

《用C#发送post请求,实现更改B站直播间标题[简单随笔].doc》

下载本文的Word格式文档,以方便收藏与打印。