0

It have been few weeks what I am trying to get output from CURL request.

static void Main(string[] args)
{
    using (var httpClient = new HttpClient())
    {
        using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://example/Login"))
        {
            request.Headers.TryAddWithoutValidation("Accept", "application/json");

            request.Content = new StringContent("{\"username\":\"username\",\"password\":\"password\"}", Encoding.UTF8, "application/json");

            var task = httpClient.SendAsync(request);
            task.Wait();
            var response = task.Result;

            Console.WriteLine(response);
            Console.ReadKey();
        }
    }
}

From this I am getting this output :

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Date: Tue, 09 Oct 2018 12:23:28 GMT
  Date: Tue, 09 Oct 2018 12:23:29 GMT
  Connection: close
  Set-Cookie: TS0119a36f=015d5689807756bd7792c622b0d146d50f8131b81e7cfa77d76c0b50114e2d09340d72b8f8ea0462c3476511b8474077967ae579e7; Path=/; Domain=.example.com
  Transfer-Encoding: chunked
  Content-Type: application/json
}

But when I execute CURL from cmd i get this (also what I need from c#)

{"code":200,"status":"success","sessionId":"35aaf800-bfdb-11e8-991a-d35512019464"}

My guess is that I have bad encoding. But I cant figure out..

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
LukasV
  • 271
  • 1
  • 3
  • 12
  • 5
    `Console.WriteLine(response);` is wrong, that's the entire response (headers, status code, etc). You want `response.Content.ReadAsStringAsync().Result` – Camilo Terevinto Oct 09 '18 at 12:35
  • You getting response header and your json is in the body. Here are some [examples](https://johnthiriet.com/efficient-api-calls/) – Renatas M. Oct 09 '18 at 12:39
  • You don't need to specify `Encoding.UTF8`, that's the default. `task.Result` blocks just like `task.Wait()`, which means you can remove `task.Wait()` – Panagiotis Kanavos Oct 09 '18 at 12:40
  • @PanagiotisKanavos UTF8 is the default in some systems, not all. Also, you have to specify it in order to use the overload that allows you to specify `application/json` – Camilo Terevinto Oct 09 '18 at 12:43

1 Answers1

1

Thanks boys, u are the best

Console.WriteLine(response.Content.ReadAsStringAsync().Result);

works for me

LukasV
  • 271
  • 1
  • 3
  • 12