在WinRT中使用HttpRequestHeaders& C#

时间:2012-06-04 13:33:01

标签: c# httpwebrequest http-headers windows-8 windows-runtime

我正在使用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;
              }
        }
}

1 个答案:

答案 0 :(得分:8)

你必须使用这样的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;
      }
    }
  }