Jade
Jade

Reputation: 501

How can I call a web api in c# using HttpClient?

So I am trying to call a api in my C# method and am not getting the response that I would be getting, if I called the api using postman or insomia.

public static async  Task GetObject()
        {
            var httpClient = new HttpClient();
            //var t = await httpClient.GetStringAsync("https://ipapi.co/json/");

            var y = await httpClient.GetAsync("https://ipapi.co/json/");


            var o = await y.Content.ReadAsStringAsync();

            var j = y.Content.ReadAsStringAsync();

        }

The api is getting my request but its not returning the right result. You should be getting this result. Click on this https://ipapi.co/json/

What am getting is this

{  
   "error":true,
   "reason":"RateLimited",
   "message":"Sign up for IP Address Location API @ https://ipapi.co"
}

But I don't get it, when am using postman

Upvotes: 0

Views: 2605

Answers (2)

Better to Use xNet.dll or Leaf.xNet.dll libraries Or restsharp one Google them I'm also new If ur interesting to contact me Discord Cyx.#4260

Upvotes: 0

Raphtaliyah
Raphtaliyah

Reputation: 207

You need to add the user-agent header.

httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1");

Upvotes: 3

Related Questions