1

我正在使用 HttpWebRequests 联系 API 并需要添加标头,但编译器告诉我该方法不存在。然而,当我查看 MSDN 时,它告诉我该方法已经存在。设置我的 UserAgent-property 也失败了。

任何人都可以帮助我吗?

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

1 回答 1

9

您将不得不像这样使用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;
      }
    }
  }
于 2012-06-04T13:55:57.963 回答