简体   繁体   中英

How do i get data from a web api into a c# windows forms app class

I'm trying to make a program in windows forms that can search for movies and series trough a web api. The program then needs to display all relevant information onto a form.

I got stuck getting the program to read from the web api. After a lot of searching i decided to put it up here.

I have some code which is mostly based on this article: https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new App());
    }

    static HttpClient client = new HttpClient();

    static async Task RunAsync()
    {
        // Update port # in the following line.
        client.BaseAddress = new Uri("http://www.omdbapi.com/?apikey=caa4fbc9&t=it");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

    }

    static async Task<Film> GetFilmAsync(string path)
    {
        Film film = null;
        HttpResponseMessage response = await client.GetAsync(path);
        if (response.IsSuccessStatusCode)
        {
            film = await response.Content.ReadAsAsync<Film>();
        }
        return film;
    }
}

Sadly it doesn't do much and i don't have any clue on what to do next. So as i said this should read data from a web api( http://www.omdbapi.com/ ). Then it has to put the selected items into a class which i can then use to make up the form.

public class Film
{
    public string Title { get; set; }
    public string Released { get; set; }
    public string Runtime { get; set; }
    public string Genre { get; set; }
    public string Director { get; set; }
    public string Actors { get; set; }
    public string Plot { get; set; }
    public string Language { get; set; }
    public string imdbRating { get; set; }
    public string totalSeasons { get; set; }
    public string Type { get; set; }
}

I hope anyone can help! Anything is appreciated!

I have changed a bit your code and it seems to work well:

async void Main()
{
    await InitClient();

    // Pass the file title to the API
    var result = await GetFilmAsync("it");
    client.CancelPendingRequests();
    client.Dispose();    
}

// Changed name to be more meaningful 
static async Task InitClient()
{
    // Remove the part with your key and the film title from the general initialization
    client.BaseAddress = new Uri("http://www.omdbapi.com/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));

}

static async Task<Film> GetFilmAsync(string title)
{
    Film film = null;

    // Compose the path adding the key and the film title
    string path = "?apikey=caa4fbc9&t=" + title;
    HttpResponseMessage response = await client.GetAsync(path);
    if (response.IsSuccessStatusCode)
    {
        string data = await response.Content.ReadAsStringAsync();

        // This is the key point, the API returns a JSON string
        // You need to convert it to your Film object.
        // In this example I have used the very useful JSon.NET library
        // that you can easily install with NuGet.
        film = JsonConvert.DeserializeObject<Film>(data);
    }
    return film;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM