C# Manipulate Postasync Response

Asked

Viewed 1,361 times

1

I have the following code:

        string json = new JavaScriptSerializer().Serialize(new
        {
            email = textBoxLogin.Text,
            password = textBoxSenha.Text
        });

        using (var client = new HttpClient())
        {
            var response = client.PostAsync(
                "https://apidomeuservidor.site/estabelecimento/auth/entrar",
                 new StringContent(json, Encoding.UTF8, "application/json"));

            var resposta = response.Result.Content.ReadAsStringAsync();
            MessageBox.Show(resposta.ToString());
        }

The answer to this call is thus:

"data": {
        "access_token": "TOKEN QUE QUERO yvOujoe7bOh5eypOZiPQ9dXrxR-XbE",
        "token_type": "bearer",
        "expires_in": 2592000
    }

How do I manipulate this answer?

The API response is being 200, only I can’t manipulate the answer

I can get the Status code and stuff, but I really can’t get the answer

Thanks in advance

  • What do you mean by manipulating? You want to "transform" your request response into an object, to use it?

  • This to use in code - being Object, list, array

3 answers

2

Install the nuget package FakeItEasy, create a fake of HttpClient.

A simple example would be something like this:

private HttpClient CreateFakeHttpClient()
{
    var fakeHttpClient = A.Fake<HttpClient>(options => options.CallsBaseMethods());
    A.CallTo(() => fakeHttpClient.SendAsync(A<HttpRequestMessage>._, A<CancellationToken>._)).ReturnsLazily((HttpRequestMessage a, CancellationToken b) => CustomSendAsync(fakeHttpClient, a, b));
    return fakeHttpClient;
}

private Task<HttpResponseMessage> CustomSendAsync(HttpClient customClient, HttpRequestMessage request, CancellationToken cancellationToken)
{
    string json = @"""data"": {
                    ""access_token"": ""TOKEN QUE QUERO"",
                    ""token_type"": ""bearer"",
                    ""expires_in"": 2592000
                    }";

    return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent(json, Encoding.UTF8, "application/json"),
    });
}

Then just test calling the method CreateFakeHttpClient. Of course this is very simple, it is possible to elaborate something much more sophisticated... But this way should already work.

2


I got it simple:

...

var response = client.PostAsync(
                    "https://apilink.site/estabelecimento/auth/entrar",
                     new StringContent(jsonEnvio, Encoding.UTF8, "application/json"));

var jsonResposta = response.Result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
MessageBox.Show(jsonResposta.ToString());

dynamic data = JsonConvert.DeserializeObject(jsonResposta);
MessageBox.Show(data.data.access_token.ToString());

I thought it was pretty simple!

2

To use the response of a request as an object it is necessary to "deserialize" the body of the response. The most used library for this is Newtonsoft (or Json.NET). Include this lib in your project and do it JsonSerializer.Deserialize<SuaClasse>(jsonString), where SuaClasse is a class you need to create in your project.

var resposta = await response.Result.Content.ReadAsStringAsync();
var objetoResposta = JsonSerializer.Deserialize<SuaClasse>(resposta);
  • As the answer (from the API) in some cases will be varied using a Dynamic makes it even easier. Thanks for the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.