How to add header to HttpWebRequest in Windows8 applicaition?(如何在 Windows8 应用程序中向 HttpWebRequest 添加标头?)
问题描述
我正在开发 C#XAML metro-ui 应用程序.我想调用一些服务并为此使用 HttpWebRequest
.HttpWebRequest
的先前实现包含 ContentLength
和 UserAgent
属性.但是 WinRT 的实现没有它.我尝试使用此 post 中描述的方法.它适用于 UserAgent
,但不适用于 ContentLength
.我试图设置 Headers
I developing C#XAML metro-ui application. I want to call some service and going to use HttpWebRequest
for this. Previous realization of HttpWebRequest
contains ContentLength
and UserAgent
properties. But realization for WinRT doesn't have it. I tried to use the approach described in this post. It works for UserAgent
but not for ContentLength
.
I've tried to set Headers
request.Headers["Content-length"] = Length;
request.Headers["User-agent"] = UserAgent;
但收到异常必须使用适当的属性或方法修改'Content-length'标头."
But received the exception "The 'Content-length' header must be modified using the appropriate property or method."
Hot 是否可以在WinRT中实现的HttpWebRequest
中设置Headers
?
Hot is it possible to set Headers
in HttpWebRequest
realized in WinRT?
推荐答案
HttpWebRequest
在 WinRT 下处于半弃用状态.以前可以在早期 .NET 平台上修改的某些标头值现在无法再用它进行修改.
HttpWebRequest
has a semi-deprecated status under WinRT. Some header values that could previously be modified on earlier .NET platforms can no longer cannot be modified with it.
似乎 HttpClient
是 HttpWebRequest 的新改进替代品,具有简单的 API 和完整的异步支持.
It seems that HttpClient
is the new and improved replacement for HttpWebRequest with a simple API and full async support.
由于您要指定 Content-Length,我假设您正在尝试向服务器发布或放置某些内容.在这种情况下,您需要酌情使用 PostAsync() 或 PutAsync().
Since you want to specify Content-Length, I assume you're trying to POST or PUT something to the server. In that case, you will want to use PostAsync() or PutAsync() as appropriate.
var req = new HttpClient();
req.DefaultRequestHeaders.Add("User-agent", UserAgent);
req.DefaultRequestHeaders.Add("Content-length", Length);
return await req.PostAsync(RequestURL, Body);
您可能实际上不需要指定 Content-length 标头,因为这些方法会根据 Body 的实际长度自动包含它,但您可以尝试任何一种方式.
You probably don't really need to specify the Content-length header, since it will be automatically included by those methods based on the actual length of the Body, but you can try it either way.
这篇关于如何在 Windows8 应用程序中向 HttpWebRequest 添加标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Windows8 应用程序中向 HttpWebRequest 添加标头?
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01