Search code examples
c#restdotnet-httpclient

Transform StringContent JSON into byte[]


Need to use this person converted into JSON inside the byte[] to finish the API. I've tried some different ways I found here, but I could not make it work. Help.

    static async void MakeRequest()
    {
        var client = new HttpClient();
        var queryString = HttpUtility.ParseQueryString(string.Empty);

            var person = new Person();
            person.id = "1234";
            person.Name = "John Doe";
            person.Email = "  ";
            person.individualIdentificationCode = "0000";
            person.order = "1";
            person.action = "DIGITAL-SIGNATURE";
            person.signurl = "https://sandbox.portaldeassinaturas.com.br/Assinatura/AssinarEletronicoFrame/152124?chave=";

            var json = JsonConvert.SerializeObject(person);
            var data = new StringContent(json, Encoding.UTF8, "application/json");
            
            // Request headers
            client.DefaultRequestHeaders.Add("Token", "{}");

            var uri = "https://api-sbx.portaldeassinaturas.com.br/api/v2/document/create?" + queryString;

            HttpResponseMessage response;

            // Request body
            byte[] byteData = Encoding.UTF8.GetBytes(data);

            using (var content = new ByteArrayContent(byteData))
            {
                content.Headers.ContentType = new 
 MediaTypeHeaderValue("application/Json");
                response = await client.PostAsync(uri, content);
            }

        }
    }
}

Solution

  • The error you are seeing is because GetBytes expects a char[] or string. But you are trying to pass a StringContent typed object and there is no conversion available to the compiler. But: you don't even need that!

    Since StringContent "is-a" ByteArrayContent ( .. "is-a" HttpContent, which is expected by PostAsync), just pass it to PostAsync:

    response = await client.PostAsync(uri, data);
    

    AND as always, of course: Don't create a new HttpClient in every call!

    HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors. - Source