make a http request with a custom body as binary and return a binary response in csharp

Here's a sample code on how to make an HTTP request with a custom binary body and receive a binary response using HttpClient and HttpRequestMessage:

main.cs
using System;
using System.Net.Http;
using System.Threading.Tasks;

public class HttpClientExample
{
    public static async Task<byte[]> PostAsync(Uri uri, byte[] body)
    {
        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage(HttpMethod.Post, uri))
        {
            request.Content = new ByteArrayContent(body);
            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

            var response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsByteArrayAsync();
                return content;
            }
            else
            {
                throw new Exception($"Failed with status code {response.StatusCode}");
            }
        }
    }
}
888 chars
29 lines

This code creates an HTTP POST request to a specified uri with a custom binary body body. The content type of the request is set to application/octet-stream. The response is read as a byte array and returned as a task. If the response status code is not success, an exception is thrown.

gistlibby LogSnag