Home > Mobile >  C# HttpClient GET returns 200 but an empty array
C# HttpClient GET returns 200 but an empty array

Time:05-19

I've been trying to use HttpClient, to connect to an API. I'm able to send a GET request and recieve the desired data that I want from it through Postman and Fiddler, without issue.

The issue is that the json file i get from the HttpClient is: []

The HttpClient gives me the Status 200 while providing me with an empty array.

    public class CoolModel
    {
         public string name { get; set; }
         public int itemId{ get; set; }
         public string Devicename{ get; set; }
    }

var username = _config["Username"];
var password = _config[":Password"];
var encoded = Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", username, password)));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encoded);
httpClient.DefaultRequestHeaders.Add("ApiKey", _config["ApiKey"]);
httpClient.DefaultRequestHeaders.Add("Accept", "*/*");
httpClient.DefaultRequestHeaders.Add("User-Agent", "C# App");

HttpResponseMessage httpResponse = httpClient.GetAsync(_config["Url"]   $"item?ID={_config["ItemId"]}&DeviceName={_config["DeviceName"]}").Result;
       
var json = await httpResponse.Content.ReadAsStringAsync();
var content = JsonConvert.DeserializeObject<List<CoolModel>>(json);

This will return the following: []

While what I want is:

[
    {
        "name":"John",
        "itemId":30,
        "Devicename":"something"
    }
]

My json that is returned is also []

CodePudding user response:

Below is a demo about using HttpClient to connect to an API, you can refer to it.

    [Route("home")]
    public class HomeController : Controller
    {

        [HttpGet]
        public async Task<IActionResult> IndexAsync()
        {
            string url = $"https://localhost:7272/weatherForecast";

            HttpClientHandler httpClientHandler = new HttpClientHandler();

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;

            HttpClient httpClient = new HttpClient(httpClientHandler)
            {
                BaseAddress = new Uri(url)
            };

            httpClient.DefaultRequestHeaders.Accept.Clear();
          
            httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");

            httpClientHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            HttpResponseMessage response = await httpClient.GetAsync(string.Empty, HttpCompletionOption.ResponseHeadersRead);

            response.EnsureSuccessStatusCode();

            var json = await response.Content.ReadAsStringAsync();

            var content = JsonConvert.DeserializeObject<List<WeatherForecast>>(json);

            return View(content);


        }

Result:

enter image description here

CodePudding user response:

My issue was that the Url

var url = _config["Url"]   $"item?ID={_config["ItemId"]}&DeviceName={_config["DeviceName"]}"

Contained empty new lines, so I had to remove the new lines. so I added the following to my url .Replace("\n", "").Replace("\r", ""));

HttpResponseMessage httpResponse = await httpClient.GetAsync(url.Replace("\n", "").Replace("\r", ""));```

CodePudding user response:

Fix your model, id should be an integer

 public class CoolModel
    {
         public string name { get; set; }
         public int id { get; set; }
         public string devicename { get; set; }
    }
  • Related