简体   繁体   English

我如何从 web api 获取数据到 ac# windows 窗体应用程序类

[英]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.我正在尝试以 Windows 形式制作一个程序,该程序可以通过 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.我遇到了让程序从 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我有一些主要基于本文的代码: https : //docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-客户

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/ ).所以正如我所说,这应该从 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何以编程方式从富文本框编译 C# Windows Forms 应用程序? C# - How do I programmatically compile a C# Windows Forms App from a richtextbox? C# C#如何在Windows Forms App中使用方法? - c# how do I use a method in a Windows Forms App? 将数据从C#asp.net网站发送到已安装的C#Windows Forms应用程序 - send data from a C# asp.net web site to an installed C# windows forms app 如何将Windows窗体应用程序从C#转换为VB? - How do I convert a windows forms app from C# to VB? 如何从 C# 中的 Windows10Forms 获取按钮句柄? - How do I get a button handle from Windows10Forms in C#? 如何将列表框中的数据添加到C#Windows窗体的SQL Server数据库中? - How do I add data from ListBox into SQL Server database in C# Windows forms? 从 Web Api 中获取数据 C# - Get data from Web Api in C# 从Windows Forms App C#轻量级数据访问 - C# Lightweight Data Access From Windows Forms App 在使用Socket类的C#Web表单应用程序中,如何发送两个连续的消息? - In a C# web forms app using the Socket class, how can I send two consecutive messages? 在C#Web API中-如何从Python HTTPBasicAuth获取用户和传递 - In C# Web API - how do I get User and Pass from Python HTTPBasicAuth
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM