从 JObject 创建 HttpRequestHeaders

    我为我的桌面软件创建了一个 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
浏览 131回答 1
1回答

胡子哥哥

您可以制作这样的扩展方法:public static class HttpClientExtensions{&nbsp; &nbsp; public static void AddHeadersFromJson(this HttpClient client, string json)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; JObject obj = JObject.Parse(json);&nbsp; &nbsp; &nbsp; &nbsp; foreach (JProperty prop in obj["header_settings"].Children<JProperty>())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; client.DefaultRequestHeaders.Add(prop.Name, (string)prop.Value);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}然后你可以这样做:using (HttpClient client = new HttpClient(hch)){&nbsp; &nbsp; client.AddHeadersFromJson(headers_json);&nbsp; &nbsp; ...}
打开App,查看更多内容
随时随地看视频慕课网APP