是否可以修改 WinRT HttpWebRequest 的用户代理?
我正在尝试将现有应用程序转换为 VS 11 开发人员预览版中的 Metro UI 应用程序。这意味着针对 WinRT 运行时运行(如果我错了,请纠正我)。它在 Windows 8 开发者预览版上运行。
我需要调用 REST API,这需要设置特定的用户代理。这在 WInRT 中似乎不可能。我有以下原始代码:
_request = WebRequest.CreateHttp(url);
_request.UserAgent = UserAgent;
但是没有为 HttpWebRequest 定义 UserAgent 属性。我还尝试过:
_request.Headers["User-Agent"] = UserAgent;
这会导致运行时异常:System.ArgumentException:必须使用适当的属性或方法修改此标头。
如何修改 User-Agent 标头?
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.
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;
But the UserAgent property is not defined for HttpWebRequest. I also tried:
_request.Headers["User-Agent"] = UserAgent;
This results in a runtime exception: System.ArgumentException: This header must be modified using the appropriate property or method.
How can I modify the User-Agent header ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
经过一番修改后,我现在已经弄清楚如何在 WinRT 中执行此操作。此版本中的 HttpWebRequest API 已发生变化,比完整的 .NET Framework 中的要差很多。但是,我可以使用新的 < 发送请求code>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:请注意,在 Windows 10 中,可以完全按照您问题中的示例进行操作。
Just to note that in Windows 10 it is possible to do it exactly like in the example in your question.