使用 httpclient 在 C# 中的请求正文中发送带有 json 字符串和文件的 post 请求

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

根据正文中的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

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

我不知道如何在正文中设置这些参数。我们有 json 数据以及要放入正文的音频文件的二进制内容。这是我的代码:

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

此请求只是一个 JSON 格式的字符串。一旦你有一个 Json 格式的字符串,你可以使用

发送它
    HttpStringContent stringContent = new HttpStringContent(
            "{ \"firstName\": \"John\" }",
            UnicodeEncoding.Utf8,
            "application/json");

    HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.PostAsync(
            uri,
            stringContent);

要首先获得 JSON 字符串,您可以:

  1. 使用字符串生成器或 string.format
  2. 手动构建字符串
  3. 使用 Json.Net 库构建它。

对于 audio.content 字段,您需要将文件转换为 base64 字符串

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