我为我的桌面软件创建了一个 API,以避免每次我想对 HttpClient 标头进行更改时进行编码和重建,但我不知道如何创建自定义 HttpRequestHeader 列表并将其作为请求标头添加到 HttpClient 中。
我正在寻找这样的解决方案:
clients.DefaultRequestHeaders = list_of_json_header_values;
到目前为止,这是我发出请求的代码:
public static string DownloadSource(string link)
{
try
{
HttpClientHandler hch = new HttpClientHandler();
hch.Proxy = null;
hch.UseProxy = false;
using (HttpClient clients = new HttpClient(hch))
{
//clients.DefaultRequestHeaders = list_of_json_header_values; ???
using (HttpResponseMessage response = clients.GetAsync(link).Result)
{
using (HttpContent content = response.Content)
{
return content.ReadAsStringAsync().Result;
}
}
}
}
catch (Exception _ex)
{
MessageBox.Show(_ex.ToString());
}
}
这是我从 JSON 获取标头的方法:
var headers_json = "json here";
var objects = JObject.Parse(headers_json);
foreach (var item in objects["header_settings"])
{
//list_of_json_header_values.Add(item.ToString()); ???
Console.WriteLine(item.ToString());
}
控制台输出:
"Cache-Control": "no-cache"
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0"
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
"Accept-Language": "en-GB,en;q=0.5"
慕工程0101907
胡子哥哥
随时随地看视频慕课网APP
相关分类