【问题标题】:Best way to call Webservice via Get通过 Get 调用 Web 服务的最佳方式
【发布时间】:2015-05-01 14:04:37
【问题描述】:

我正在调用我通过 HTTP Get 访问的第 3 方 API。我有一个使用 HttpWebRequest 和 HttpWebResponse 调用此 API 的工作示例,它工作正常。我想确保这是最佳实践,或者我应该使用其他东西。这不是一个 Web 解决方案,因此它没有内置 MVC/Web Api 引用。这是一些示例代码

     protected WebResponse executeGet(string endpoint, Dictionary<string, string> parameters, bool skipEncode = false)
    {
        string urlPath = this.baseURL + endpoint + "?" +
                         createEncodedString(parameters, skipEncode);
        Console.WriteLine("Sending to: " + urlPath);
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urlPath);
        req.Method = "GET";
        return req.GetResponse();
    }

这是调用 Get APIs 的首选方式吗?

【问题讨论】:

  • 这不是 SO 的主题。这可能是一个很好的代码审查候选者,尽管您可能需要提供有关您的 .net 框架的更多信息和任何其他系统信息,然后其他人才能提供帮助。

标签: c# http-get


【解决方案1】:

虽然我知道 SO 不鼓励“最佳实践”问题,但我看到的 WebAPI 调用的“Microsoft 推荐”方式是在 Microsoft.AspNet.WebApi.Client NuGet 包中使用 HttpClient。除了 Windows 和 Web 项目,Windows Phone 和 Windows Store 项目也支持此包。

这是他们的示例 GET 代码的样子:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:9000/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    HttpResponseMessage response = await client.GetAsync("api/products/1");
    if (response.IsSuccessStatusCode)
    {
        Product product = await response.Content.ReadAsAsync<Product>();
        Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
    }
}

FMI,见Calling a Web API From a .NET Client in ASP.NET Web API 2 (C#)

【讨论】:

  • 谢谢,这就是我要找的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-01
  • 2011-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多