Using HttpRequestHeaders in WinRT amp; C#(在 WinRT amp; 中使用 HttpRequestHeadersC#)
问题描述
我正在使用 HttpWebRequests 联系 API 并需要添加标头,但编译器告诉我该方法不存在.然而,当我查看 MSDN 时,它告诉我该方法已经存在.设置我的 UserAgent-property 也失败了.
I'm using HttpWebRequests to contact an API and need to add a header but the compiler tells me that the method does not exists. Yet, when I check MSDN, it tells me that the method already exists. Setting my UserAgent-property fails as well.
谁能帮帮我?
try{
HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create(url);
wr.Method = "GET";
wr.Headers.Add(System.Net.HttpRequestHeader.Authorization, string.Format("Bearer {0}", _accessToken));
wr.UserAgent = _appNameAndContact;
var resp = (System.Net.HttpWebResponse) await wr.BetterGetResponse();
if (resp.StatusCode == System.Net.HttpStatusCode.OK)
{
using (var sw = new System.IO.StreamReader(resp.GetResponseStream()))
{
var msg = sw.ReadToEnd();
User usr = JsonConvert.DeserializeObject<User>(msg);
//var results = JSONHelper.Deserialize<User>(msg);
return usr;
}
}
}
推荐答案
您将不得不使用 HttpRequestMessage 像这样:
You will have to use a HttpRequestMessage like this:
using (var httpClient = new HttpClient())
{
var url = new Uri("http://bing.com");
var accessToken = "1234";
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url))
{
httpRequestMessage.Headers.Add(System.Net.HttpRequestHeader.Authorization.ToString(),
string.Format("Bearer {0}", accessToken));
httpRequestMessage.Headers.Add("User-Agent", "My user-Agent");
using (var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage))
{
// do something with the response
var data = httpRequestMessage.Content;
}
}
}
这篇关于在 WinRT & 中使用 HttpRequestHeadersC#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 WinRT & 中使用 HttpRequestHeadersC#
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01