我最近开始学习.NET Core,因为它提供了一些HttpClient的特性(例如设置keep-alive标头上限)。
我正在使用2.1 net core和C# 7.3。我的问题
我的问题主要是关于设置“Accept”和“Accept-Language”标头。我尝试访问的网站将这两个标头解析为原样,这意味着它们必须具有完全相同的格式(包括空格)。
使用Fiddler(和其他一些工具)来捕获我的请求。
- 我捕获的“Accept”标头如下所示:(格式不正确)
text/html, application/xhtml+xml, application/xml; q=0.9, image/webp, image/apng, */*; q=0.8, application/signed-exchange; v=b3
代替:
(正确格式)
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
"Accept-Language" 头部应该如下所示:(格式不正确)
en-US, en; q=0.9, ar; q=0.8, und; q=0.7
而不是:(正确格式)
en-US,en;q=0.9,ar;q=0.8,und;q=0.7
我正在使用HttpRequestMessage和HttpClient模拟GET请求。
我尝试过的方法:
- 尝试在HttpClient实例中设置我的标头,并使用自己的标头触发HttpRequestMessage,但都没有起作用。
- 尝试了许多在线解决方案,包括this,但都没有起作用。
- 通过多个
.Headers.TryAddWithoutValidation
来分割标题。 - 也尝试过HttpWebRequests,但没有成功。需要注意的一点是,由于我的项目需要,我也想继续使用HttpClient。
您将在下面找到我的当前代码
var client = new HttpClient(new HttpClientHandler() { UseCookies = false,
AllowAutoRedirect = false,
Proxy = new WebProxy("localhost:8888") });
var httpReq = new HttpRequestMessage(HttpMethod.Get, $"myurl");
httpReq.Headers.TryAddWithoutValidation("Host", "myurl");
httpReq.Headers.TryAddWithoutValidation("Connection", "keep-alive");
httpReq.Headers.TryAddWithoutValidation("Cookie", $"cookie");
httpReq.Headers.TryAddWithoutValidation("Upgrade-Insecure-Requests", "1");
httpReq.Headers.TryAddWithoutValidation("User-Agent", Data.user_agent);
httpReq.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate, br");
httpReq.Headers.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
httpReq.Headers.TryAddWithoutValidation("Referer", Data.homeUrl);
httpReq.Headers.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.9,ar;q=0.8,und;q=0.7");
req = await client.SendAsync(httpReq);
如前所述,所有其他标题都正常工作。只有这两个 Accept 和 Accept-Language 的输入方式不同。
httpReq.Headers.AcceptLanguage.Add("en-US");
等方式。 - spodger