0

I want to get 2 data like "phone" and "username" from this URL: "http://localhost/api/basic.php?id={id}" in C#

I Use this code to get

string api = "http://localhost/api/basic.php?id=";
api += TxtID.Text;
WebClient client = new WebClient();
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(api);
myHttpWebRequest.Referer = "http://localhost/api/form.html";

1 Answer 1

2

The modern way (for .net 5 and 4.x) is:

using System.Net.Http.Json;  // add the NuGet package

private HttpClient client = new HttpClient();
private async void MyForm_Load(object sender, EventArgs e)
{           
    MyClass data = await client.GetFromJsonAsync<MyClass>(api);
    ...
}

do not Dispose the HttpClient.

The package is not part of the default WinForms template, add System.Net.Http.Json from NuGet.

Sign up to request clarification or add additional context in comments.

5 Comments

Make HttpClient static and it looks perfect
You can initialize a static Lazy<HttpClient>, if necessary. A default HttpClientHandler can be setup directly with a Lambda.
I got this Error: "Http" does not exist in System.Net!
You have to Add the System.Net.Http.Json nuget package. See the comment.
When you make the HttpClient static, you should also consider to make it readonly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.