# HttpClient and you

**URL:** <https://extensions.streamer.bot/t/httpclient-and-you/1369>\
**Category:** C# Tips\
**Tags:** csharp\
**Created:** [May 12, 2024, 10:54pm UTC](https://extensions.streamer.bot/t/httpclient-and-you/1369 "2024-05-12T22:54:15Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![rondhi](https://extensions.streamer.bot/user_avatar/extensions.streamer.bot/rondhi/32/24_2.png) [@rondhi](https://extensions.streamer.bot/u/rondhi)\
**Post date:** [May 12, 2024, 10:54pm UTC](https://extensions.streamer.bot/t/httpclient-and-you/1369/1 "2024-05-12T22:54:16Z")

</div>

In your C# journey, you may require the use of HttpClient. You may find examples that have you put HttpClient in a using statement. It’s been said that this is not proper practice.

### Sources

- [You’re using HttpClient wrong and it is destabilizing your software](https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/)
- [You're (probably still) using HttpClient wrong and it is destabilizing your software](https://josef.codes/you-are-probably-still-using-httpclient-wrong-and-it-is-destabilizing-your-software/)

### Summary

Using `HttpClient` within a `using()` statement is not recommended due to the potential for socket exhaustion and performance degradation caused by frequent creation and disposal of TCP connections. Each `HttpClient` instance manages its own connection pool, and creating a new instance for each request can lead to inefficient resource usage. Instead, reusing `HttpClient` instances across multiple requests within the lifetime of the application or a specific component is advised to minimize overhead and improve performance. By managing `HttpClient` instances properly and reusing them as needed, developers can avoid issues associated with excessive resource allocation and ensure optimal utilization of network resources.

## Example 1

The following is an example of a reusable HttpClient. This C# example will check the broadcaster’s Twitch account age using the decapi API and return it as `%accountAge%`:

```cs
using System;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class CPHInline
{
    private static readonly HttpClient _httpClient = new HttpClient{Timeout = TimeSpan.FromSeconds(30)};

    public void Init()
    {
        _httpClient.DefaultRequestHeaders.Clear(); // Optionally clear headers if needed
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
    }

    public bool Execute()
    {
        // Get broadcaster info
        TwitchUserInfo broadcastInfo = CPH.TwitchGetBroadcaster();
        string username = broadcastInfo.UserLogin;

        // Specify the URL you want to send the GET request to
        string apiUrl = $"https://decapi.me/twitch/accountage/{username}";

        string jsonResponse = GetRequestAsync(apiUrl).GetAwaiter().GetResult();

        if (string.IsNullOrEmpty(jsonResponse))
        {
            CPH.LogError("jsonResponse returned null");
            return false;
        }
        else
        {
            CPH.LogDebug($"Account age: '{jsonResponse}'");
            CPH.SetArgument("accountAge", jsonResponse);
            return true;
        }
    }

    private async Task<string> GetRequestAsync(string apiUrl)
    {
        try
        {
            // Send the GET request and get the response
            HttpResponseMessage response = await _httpClient.GetAsync(apiUrl);

            // Check if the request was successful
            if (!response.IsSuccessStatusCode)
            {
                // If the request was not successful, log the error
                CPH.LogError($"{response.StatusCode} - {response.ReasonPhrase}");
                return null;
            }

            // Read and print the content of the response
            string content = await response.Content.ReadAsStringAsync();
            return content;
        }
        catch (Exception ex)
        {
            // Handle exceptions specific to the asynchronous operation
            CPH.LogError(ex.Message);
            return null;
        }
    }
}

```

## Example 2

I’ve attached an import code providing a full working example. This example will check if the broadcaster is currently live on Twitch and return the variable `%isLive%` as either True or False  
[httpClientExample.sb](https://extensions.streamer.bot/uploads/short-url/2YNGqerx2xn32aA9K2c7dtpGzgv.sb) (3.9 KB)
