使用WinRT的中&C#HttpRequestHeaders(Using HttpRequestHe

2019-07-29 17:44发布

我使用HttpWebRequests联系的API,并需要添加一个头,但编译器告诉我,该方法不存在。 然而,当我检查的MSDN,它告诉我,该方法已经存在。 设置我的UserAgent属性也将失败。

任何人都可以帮助我吗?

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;
              }
        }
}

Answer 1:

你将不得不使用HttpRequestMessage这样的:

  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;
      }
    }
  }


文章来源: Using HttpRequestHeaders in WinRT & C#