我為我的桌面軟件創建了一個 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"
從 JObject 創建 HttpRequestHeaders
慕工程0101907
2022-07-10 10:24:05