【问题标题】:Sending a post request with json string and a file in the body of the request in C# using httpclient使用 httpclient 在 C# 中发送带有 json 字符串的 post 请求和请求正文中的文件
【发布时间】:2016-08-15 01:53:50
【问题描述】:

根据https://cloud.google.com/speech/reference/rest/v1beta1/speech/asyncrecognize#authorization ,我正在尝试向正文中的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();

【问题讨论】:

    标签: c# http-post httpclient google-speech-api


    【解决方案1】:

    这个请求只是一个 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. 使用 Json.Net 库来构建它。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      • 2015-03-22
      • 1970-01-01
      • 2019-07-19
      • 2021-01-03
      相关资源
      最近更新 更多