PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 11, 2022

[FIXED] How to get data by api use Windows Form

 November 11, 2022     c#, httpclient, winforms     No comments   

Issue

On the browser, I could get data like this.(JSON format) enter image description here

I want to perform HTTP requests and get data on WinForm. How can I do to make it like the below picture?

enter image description here

I have referred to some relevant information. But I am confused how to start (like I should write code in Form1.cs or add new class, should I create model...)

How to make HTTP POST web request

How to return async HttpClient responses back to WinForm?

Can I use HttpClient Method? Thanks for answer and suggestion.


(New edit)

https://www.youtube.com/watch?v=PwH5sc-Q_Xk

I also learned from this video, But I got error message.

No MediaTypeFormatter is available to read an object of type 'IEnumerable`1' from content with media type 'text/html'.

My code

Form1.cs

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Net.Http;
using System.Net.Http.Formatting;

namespace _123
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            HttpClient clint = new HttpClient();
            clint.BaseAddress = new Uri("http://localhost:8888/");
            HttpResponseMessage response = clint.GetAsync("PersonList").Result;

            var emp = response.Content.ReadAsAsync<IEnumerable<ImgList>>().Result;
            dataGridView1.DataSource = emp;
        }
    }
}

ImgList.cs (Is this Model?)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace _123
{
    class ImgList
    {
        public int id { get; set; }
        public string name { get; set; }
        public int age { get; set; }
    }
}

enter image description here

enter image description here


Solution

On the browser, I could get data like this.(JSON format)

This is means you are making an HttpGet call with no parameters as I can see from the Url and in any case there's no HttpBody. For any other call like HttpPost, you have to use a tool like Postman, Fiddler

Following is the simple code to make a Http Get call using C#:

// Create HttpClient
var client = new HttpClient { BaseAddress = new Uri("http://localhost:8888/") };

// Assign default header (Json Serialization)
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(ApiConstant.JsonHeader));    

// Make an API call and receive HttpResponseMessage
var responseMessage = await client.GetAsync("PersonList", HttpCompletionOption.ResponseContentRead);

// Convert the HttpResponseMessage to string
var resultArray = await result.Content.ReadAsStringAsync();

// Deserialize the Json string into type using JsonConvert
var personList = JsonConvert.DeserializeObject<List<Person>>(resultArray);

How it works

  • HttpClient is object which encompass the api service address
  • We ensure that assigned header is Json type for serialization / communication
  • Make an Async Http Get Call
  • HttpResponseMessage is used to extract string, which is de-serialized into List<Person> using NewtonSoft Json

Please note Async call means encompassing method shall be Async

Expected Schema for the Person class to fill the List<Person> using de-serialization:

public class Person
{
  public int id {get;set;}
  public string Name {get;set;}
  public int age {get;set;}
}

Where to call the code - Winform / Add new class

Standard mechanism would be to create a generic helper library / class, from which all the API calls are done, results are fetched, winform shall just do the data binding, not have the processing code



Answered By - Mrinal Kamboj
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing