是否可以修改 WinRT HttpWebRequest 的用户代理?用户、WinRT、HttpWebRequest

2023-09-06 14:14:45 作者:浅眉

我正在尝试将现有应用程序转换为 VS 11 开发人员预览版中的 Metro UI 应用程序.这意味着针对 WinRT 运行时运行(如果我错了,请纠正我).这在 Windows 8 Developer Preview 上运行.

I am trying to convert an existing app to a Metro UI app in VS 11 Developer Preview. This means running against the WinRT runtime (correct me if I'm wrong). This runs on the Windows 8 Developer Preview.

我需要调用 REST API,这需要设置特定的用户代理.这在 WInRT 中似乎是不可能的.我有以下原始代码:

I need to call a REST API, which requires a specific user-agent to be set. This doesn't seem to be possible in WInRT. I have the following original code:

_request = WebRequest.CreateHttp(url);
_request.UserAgent = UserAgent;

但是没有为 HttpWebRequest 定义 UserAgent 属性.我也试过了:

But the UserAgent property is not defined for HttpWebRequest. I also tried:

_request.Headers["User-Agent"] = UserAgent;

这会导致运行时异常:System.ArgumentException:必须使用适当的属性或方法修改此标头.

如何修改 User-Agent 标头?

How can I modify the User-Agent header ?

推荐答案

经过一番修改,我现在已经弄清楚了如何在 WinRT 中做到这一点.此版本中的 HttpWebRequest API 已更改为比完整的 .NET Framework 中的要差得多.但是,我可以使用新的 HttpClient API,它将允许我发送用户代理标头:

After some tinkering around, I have now worked out how to do this in WinRT. The HttpWebRequest API has changed in this version to be a lot poorer than in the full .NET Framework. However, I can send a request with the new HttpClient API, which will allow me to send the user-agent header:

var req = new HttpClient(handler)
var message = new HttpRequestMessage(HttpMethod.Get, url);
message.Headers.Add("User-Agent", "myCustomUserAgent");
var response = await req.SendAsync(message);