简体   繁体   中英

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM