本文介绍了在 WinRT & 中使用 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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!