Reputation: 37
I'm new to APIs, so I've been trying to use a web request to GET information from Reddit, since the API is unlocked. I've been able to use the right URL to get information using a REST client extension, but I want to implement the body of the data and simply just print it out to a web page.
I know this is easier with python, but they use C#/ASP.NET at my work. I've looked off of tutorials such as:
http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client
I was only able to obtain a header when I used this tutorial and my code is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace API_TESTING
{
class Product
{
public string Name { get; set; }
public double Price { get; set; }
}
class Program
{
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using(var client = new HttpClient())
{
//TODO - send HTTP requests
client.BaseAddress = new Uri("http://www.reddit.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//-----
HttpResponseMessage response = await client.GetAsync("r/todayilearned/new.json");
if(response.IsSuccessStatusCode)
{
Console.Write(response);
}
}
}
}
}
Can someone explain how to use ASP.NET for API calls? or link to other up-to-date tutorials? Thank you.
Upvotes: 0
Views: 4128
Reputation: 2565
You're almost there. After you get the response, you need to read its content.
var response = await _client.GetAsync(uri);
if (response.IsSuccessStatusCode) {
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
You might want to check out the RedditSharp project to see how others have done this.
Btw, the tutorial you linked to does almost exactly what I answered with under the Getting a Resource (HTTP GET) section. Only difference is they used the generic ReadAsAsync
while you can use ReadAsStringAsync
if you're just writing the body to the console.
Upvotes: 2