using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
namespace Add_share
{
public class Program
{
//请填写这三个值
private const string client_id = "client_id";
private const string app_secret = "app_secret";
private const string biz_code = "biz_code";
private const string OpenPlatformHttpHost = "https://member.bilibili.com";
public static void Main()
{
var resp = ApiRequest("{\"scene_code\": \"ARC_APP_SHARE\",\"biz_code\":\"" + biz_code + "\",\"common_msg\":\"{}\"}", "/arcopen/fn/resource/add_share").Result;
Console.WriteLine($"\nrespjosn:\n-----------------------------\n");
WriteLog(resp);
Console.ReadKey();
}
public static async Task<string> ApiRequest(string reqJson, string requestUrl)
{
Console.WriteLine($"请求地址:{requestUrl}");
var header = new CommonHeader
{
ContentType = "application/json",
ContentAcceptType = "application/json",
Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(),
SignatureMethod = "HMAC-SHA256",
SignatureVersion = "1.0",
Authorization = "",
Nonce = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
AccessKeyId = client_id,
ContentMD5 = Md5(reqJson)
};
Console.WriteLine($"\nreqjosn:\n----------------------------\n");
WriteLog(reqJson);
header.Authorization = CreateSignature(header, app_secret);
using var client = new HttpClient { BaseAddress = new Uri(OpenPlatformHttpHost + requestUrl) };
client.DefaultRequestHeaders.Clear();
foreach (var item in header.ToMap())
{
if (item.Key.ToLower() != "content-type")
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
var content = new ByteArrayContent(Encoding.UTF8.GetBytes(reqJson));
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var response = await client.PostAsync(OpenPlatformHttpHost + requestUrl, content);
var respJson = await response.Content.ReadAsStringAsync();
return respJson;
}
public static string CreateSignature(CommonHeader header, string accessKeySecret)
{
var sStr = header.ToSortedString();
return HmacSHA256(accessKeySecret, sStr);
}
public static string Md5(string str)
{
using var md5 = MD5.Create();
var result = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
return BitConverter.ToString(result).Replace("-", "").ToLower();
}
public static string HmacSHA256(string key, string data)
{
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(data));
return BitConverter.ToString(hash).Replace("-", "").ToLower();
}
//格式化输出JSON-测试用
private static void WriteLog(string response)
{
using (JsonDocument doc = JsonDocument.Parse(response))
{
// 创建 JsonWriterOptions,设置为格式化输出
JsonWriterOptions options = new JsonWriterOptions
{
Indented = true
};
// 创建一个内存流
using (var stream = new System.IO.MemoryStream())
{
// 使用 Utf8JsonWriter 来写入内存流
using (var writer = new Utf8JsonWriter(stream, options))
{
doc.WriteTo(writer);
}
// 将内存流转换为字符串
string formattedJson = System.Text.Encoding.UTF8.GetString(stream.ToArray());
// 重新序列化以确保汉字不被转义
var jsonObject = System.Text.Json.JsonSerializer.Deserialize<object>(formattedJson);
string finalOutput = System.Text.Json.JsonSerializer.Serialize(jsonObject, new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
// 输出格式化后的 JSON 到终端
Console.WriteLine(finalOutput);
}
}
}
}
public class CommonHeader
{
public string ContentType { get; set; }
public string ContentAcceptType { get; set; }
public string Timestamp { get; set; }
public string SignatureMethod { get; set; }
public string SignatureVersion { get; set; }
public string Authorization { get; set; }
public string Nonce { get; set; }
public string AccessKeyId { get; set; }
public string ContentMD5 { get; set; }
public Dictionary<string, string> ToMap()
{
return new Dictionary<string, string>
{
{ "x-bili-timestamp", Timestamp },
{ "x-bili-signature-method", SignatureMethod },
{ "x-bili-signature-nonce", Nonce },
{ "x-bili-accesskeyid", AccessKeyId },
{ "x-bili-signature-version", SignatureVersion },
{ "x-bili-content-md5", ContentMD5 },
{ "Authorization", Authorization },
{ "Content-Type", ContentType },
{ "Accept", ContentAcceptType }
};
}
public Dictionary<string, string> ToSortMap()
{
return new Dictionary<string, string>
{
{ "x-bili-timestamp", Timestamp },
{ "x-bili-signature-method", SignatureMethod },
{ "x-bili-signature-nonce", Nonce },
{ "x-bili-accesskeyid", AccessKeyId },
{ "x-bili-signature-version", SignatureVersion },
{ "x-bili-content-md5", ContentMD5 }
};
}
public string ToSortedString()
{
var hMap = ToSortMap();
var hSil = hMap.Keys.ToList();
hSil.Sort();
var sign = hSil.Aggregate("", (current, v) => current + (v + ":" + hMap[v] + "\n"));
return sign.TrimEnd('\n');
}
}
public class BaseResp
{
public int code { get; set; }
public string message { get; set; }
public string request_id { get; set; }
public string data { get; set; }
}
}