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 的用户代理?
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
