0
var client = new RestClient("http://10.0.0.244:8885/terminal/info");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("apikey", "adasdsadasd");
var body = @"{}";
request.AddParameter("application/json", body,  ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

Could someone, please, help me write this code with HttpClient? I try following code.

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://10.0.0.244:8885/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Clear();
    HttpRequestMessage request = new HttpRequestMessage();
    request.Method = HttpMethod.Post;
    request.RequestUri = new Uri($"{client.BaseAddress}/terminal/info");
    request.Headers.Add("apikey", "adasdsadasd");
    var body = Newtonsoft.Json.JsonConvert.SerializeObject(new { });
    request.Content = new StringContent(body, Encoding.UTF8, "application/json");//CONTENT-TYPE header
    request.Content.Headers.Clear();
    request.Content.Headers.ContentLength = 2;
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    HttpResponseMessage response = client.SendAsync(request).GetAwaiter().GetResult();
    var x = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();

}

But it response with Status Code 400 (ParseError)

  • Your JS is passing the content as `text/plain` and your `HttpClient` is passing `application/json`. Does your endpoint expect `text/plain`? Also this is far more verbose than it needs to be. – hawkstrider Aug 22 '22 at 13:44

1 Answers1

0

You can accomplish what you are trying to do with much less code. Also this should be in an async method. Below is an example

internal async Task<string> GetResponse()
{
    using var client = new HttpClient();
    client.BaseAddress = new Uri("http://10.0.0.244:8885/");
    client.DefaultRequestHeaders.Clear();
    client.DefaultRequestHeaders.Add("apikey", "adasdsadasd");
    var content = new StringContent("{}", Encoding.UTF8, "text/plain");
    var response = await client.PostAsync("/terminal/info", content);
    if (response.IsSuccessStatusCode)
    {
        return await response.Content.ReadAsStringAsync();
    }
    return null;
}
hawkstrider
  • 4,141
  • 16
  • 27