如何在 Windows8 应用程序中向 HttpWebRequest 添加标头?

How to add header to HttpWebRequest in Windows8 applicaition?(如何在 Windows8 应用程序中向 HttpWebRequest 添加标头?)

本文介绍了如何在 Windows8 应用程序中向 HttpWebRequest 添加标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 C#XAML metro-ui 应用程序.我想调用一些服务并为此使用 HttpWebRequest .HttpWebRequest 的先前实现包含 ContentLengthUserAgent 属性.但是 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 添加标头?

基础教程推荐