PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 11, 2022

[FIXED] How to get and print response from Httpclient.SendAsync call

 November 11, 2022     asynchronous, c#, httpclient     No comments   

Issue

I'm trying to get a response from a HTTP request but i seem to be unable to. I have tried the following:

public Form1() {     

    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("someUrl");
    string content = "someJsonString";
    HttpRequestMessage sendRequest = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);
    sendRequest.Content = new StringContent(content,
                                            Encoding.UTF8,
                                            "application/json");

Send message with:

    ...
    client.SendAsync(sendRequest).ContinueWith(responseTask =>
    {
        Console.WriteLine("Response: {0}", responseTask.Result);
    });
} // end public Form1()

With this code, i get back the status code and some header info, but i do not get back the response itself. I have tried also:

  HttpResponseMessage response = await client.SendAsync(sendRequest);

but I'm then told to create a async method like the following to make it work

private async Task<string> send(HttpClient client, HttpRequestMessage msg)
{
    HttpResponseMessage response = await client.SendAsync(msg);
    string rep = await response.Content.ReadAsStringAsync();
}

Is this the preferred way to send a 'HttpRequest', obtain and print the response? I'm unsure what method is the right one.


Solution

here is a way to use HttpClient, and this should read the response of the request, in case the request return status 200, (the request is not BadRequest or NotAuthorized)

string url = 'your url here';

// usually you create on HttpClient per Application (it is the best practice)
HttpClient client = new HttpClient();

using (HttpResponseMessage response = client.GetAsync(url).GetAwaiter().GetResult())
{
    using (HttpContent content = response.Content)
    {
         var json = content.ReadAsStringAsync().GetAwaiter().GetResult();
    }
}

and for full details and to see how to use async/await with HttpClient you could read the details of this answer



Answered By - Hakan Fıstık
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing