我为桌面软件创建了一个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"
答案 0 :(得分:2)
您可以创建如下扩展方法:
Started PUT "/rooms/undefined/connected" for 127.0.0.1 at 2019-01-06 09:29:13 -0800
Processing by RoomsController#connected as */*
Parameters: {"room"=>{"name"=>"New_room"}, "room_id"=>"undefined"}
From: /Users/us186007/Desktop/WebApps/goldenyears/app/controllers/rooms_controller.rb @ line 39 RoomsController#connected:
36: def connected
37: binding.pry
38: # @room = Room.find params[:id]
=> 39: @room.update_attributes(params[:name])
40: end
[1] pry(#<RoomsController>)> @room
=> nil
那么你可以做:
public static class HttpClientExtensions
{
public static void AddHeadersFromJson(this HttpClient client, string json)
{
JObject obj = JObject.Parse(json);
foreach (JProperty prop in obj["header_settings"].Children<JProperty>())
{
client.DefaultRequestHeaders.Add(prop.Name, (string)prop.Value);
}
}
}