Search code examples
c#http-posthttpclientgoogle-speech-api

Sending a post request with json string and a file in the body of the request in C# using httpclient


According to https://cloud.google.com/speech/reference/rest/v1beta1/speech/asyncrecognize#authorization , I am trying to send a post request with the following information to https://speech.googleapis.com/v1beta1/speech:asyncrecognize in the body:

{
  "config": {
  "encoding": 'FLAC',
  "sampleRate": 16000,
  },
  "audio": {
  "content": <a base64-encoded string representing an audio file>,
  },
}

I don't know how to set these parameters in the body. We have json data as well as the binary content of an audio file to put in the body. This is my code:

        string mServerUrl = @"https://speech.googleapis.com/v1beta1/speech:asyncrecognize";

        MultipartFormDataContent content = new MultipartFormDataContent();
        content.Add(new StringContent("config"), "\"encoding\":\"FLAC\",\"sampleRate\":16000");
        content.Add(CreateFileContent("audio.flac"));

        HttpClient mHttpClient = new HttpClient();
        HttpResponseMessage mResponse = null;

        mResponse = await mHttpClient.PostAsync(mServerUrl, content);

        string responseBodyAsText = await mResponse.Content.ReadAsStringAsync();

Solution

  • This request is just one JSON formatted string. Once you have a string in Json format you can send it using

        HttpStringContent stringContent = new HttpStringContent(
                "{ \"firstName\": \"John\" }",
                UnicodeEncoding.Utf8,
                "application/json");
    
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.PostAsync(
                uri,
                stringContent);
    

    To get the JSON string in the first place you can:

    1. build the string up manually with a string builder or string.format
    2. use the Json.Net library to build this.

    For the audio.content field you need to convert your file to a base64 string

    Public Function ConvertFileToBase64(ByVal fileName As String) As String
        Return Convert.ToBase64String(System.IO.File.ReadAllBytes(fileName))
    End Function