Reputation: 2909
I am calling a 3rd party API that I access with an HTTP Get. I have a working example to call this API using HttpWebRequest and HttpWebResponse and it works fine. I wanted to make sure this is best practice, or should I be using something else. This is not a Web solution so it does not have MVC/Web Api references built in. Here is some sample code
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();
}
Is this the preferred way to call Get Apis?
Upvotes: 0
Views: 1957
Reputation: 1393
While I know SO discourages "best-practice" questions, the "Microsoft recommended" way I've seen WebAPIs called is using HttpClient
in the Microsoft.AspNet.WebApi.Client
NuGet package. Besides Windows and web projects, this package is supported for Windows Phone and Windows Store projects too.
Here's what their sample GET code looks like:
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, see Calling a Web API From a .NET Client in ASP.NET Web API 2 (C#)
Upvotes: 1