Is it possible to modify the User-Agent for a WinRT HttpWebRequest?(是否可以修改 WinRT HttpWebRequest 的用户代理?)
问题描述
我正在尝试将现有应用程序转换为 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);
这篇关于是否可以修改 WinRT HttpWebRequest 的用户代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以修改 WinRT HttpWebRequest 的用户代理?
基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
