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

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

问题描述

我正在开发C#\ XAML metro-ui应用程序.我想打电话给某些服务,并为此使用HttpWebRequest. HttpWebRequest的先前实现包含ContentLengthUserAgent属性.但是WinRT的实现没有它.我尝试使用此帖子中描述的方法.它适用于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."

是否可以在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 是具有简单API和完全异步支持的HttpWebRequest的新改进版.

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添加标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆