BrainBeast

Hunt down knowledge with our help

FAQ about HTTP Client with examples

What is HTTP Client?

In client-server model Server is the one who handle requests and send responses, Client is the one who send requests and handle responses.
client-server
Generally speaking, Client is a program, library or a program method that:

  1. Sends request with some data to the server
  2. Recieves response messege from server

That list is a minimal requirements to be considered a client.

Client can be both a high-level many functional library and Two request-response method code.

Wisely chosen Client is crucial for the performance of the web application that uses external API or deals with a large number of requests.
As a rule each language platform has its native tool to do client’s job.

Why do you need HTTP Client?

Nowadays, there are some standarts of biulding HTTP request messeges in client-server model. That is how various web systems can communicate. As you can see in RFC documentation, there are a lot of information about what is HTTP and how to use it. Usually a common developer doesn’t have time to look through it. But he doesn’t really have to.

Client is developed to match standarts of a protocol it works with and architecture of this protocol usage (for instance, REST). In our case it is HTTP or HTTPS.

Client is a way to simplify a whole work with sending and obtaining data, because:

  • it takes into account all protocol specification
  • it is designed to be high performance at low level and simple to use at hign level
  • developer doesn’t need to know how protocol works

HTTP Request Methods

HTTP Requests are widely used to work with external databases by means of API. In order to make API usage more predictable and easy requests are divided by methods:

  • GET – to pass info in url (e.g https://[site url][parameters]) and obtaine public data
  • POST – to pass private info
  • DELETE – to pass private info in order to request removal of something from database
  • PUT – to pass private info in order to request update of something in database
  • and others

HTTP Client examples

webapplication

.NET C# HTTP Client

System.Net.Http namespace provides a lot of classes for work in web. HttpClient is a modern and fast HTTP .Net Client.

...
   using System.Net.Http;  //adding Http namespace
...
   HttpClient _client=new HttpClient();

   string url="http://www.brainbeast.best";  //some url

   string resp = await _client.GetStringAsync(url);  //get request, resp will contain html code of a webpage
...
Javascript HTTP Client

Web version of JS has XMLHttpRequest object that can send and recieve http messeges, set request method and work in async regime.

...
    function PostRequest() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            
          var resp=this.responseText;  //response messege

        }
    };
    
    xhttp.open("POST", "http://someurl", true);  //setting Method, url, async regime (true/false)
    xhttp.send("private data");  //private data to send
}
...
PHP HTTP Client

By means of cURL PHP running servers can execute http requests. cURL is not the only option.

...
    $crl = curl_init();

    curl_setopt($crl, CURLOPT_URL,"https://some_url");

    curl_setopt($crl, CURLOPT_POST, 1);

    curl_setopt($crl, CURLOPT_POSTFIELDS,"private post data");

    curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);

    $resp = curl_exec($crl);

    curl_close ($crl);

    echo $resp;
...

How to download image with HTTP Client on C#?

...
   HttpClient _client=new HttpClient();
   byte[] buffer = null;
   try
   {       
      HttpResponseMessage task = await _client.GetAsync("https://www.brainbeast.best/wp-content/uploads/2020/05/client-server.jpg");
      Stream task2 = await task.Content.ReadAsStreamAsync();
      using (MemoryStream ms = new MemoryStream())
      {
        await task2.CopyToAsync(ms);
        buffer = ms.ToArray();
      }
      File.WriteAllBytes("C:/client-server.jpg", buffer);  //path to save image and bites of this image
   }
   catch
   {

   }
...

How to set timeout in C# HTTP Client?

...
   HttpClient _client=new HttpClient();
   _client.Timeout = TimeSpan.FromSeconds(300);
...

How to add Custom Header to HTTP Request on C#?

...
   HttpClient _client=new HttpClient();
   client.DefaultRequestHeaders.Add("Some header", "some value");
...

How to create HTTP POST request and send JSON data on C#?

First option is to install Microsoft.AspNet.WebApi.Client from Nuget.

...
class Person
{
   public string Name {get;set;}
   public string Surname {get;set;}
}
...
   Person person=new Person {Name ="Andy", Surname="Smith"};  //you can post any class with public fields

   HttpClient _client=new HttpClient();

   var response = await client.PostAsJsonAsync("http://endpoint", person);

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

Second option:

...
   HttpClient _client=new HttpClient();

   var values = new Dictionary<string, string>
      {
        { "username", "andy" },
        { "password", "12345678" }
      };

   var content = new FormUrlEncodedContent(values);

   var response = await _client.PostAsync($"https://some endpoint", content);

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

LEAVE A RESPONSE

Related Posts