Using HttpRequestHeaders in WinRT & C#

2020-05-07 09:24发布

问题:

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.

Can anyone help me please?

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

回答1:

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