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

时间:2016-08-15 01:53:51

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

根据https://cloud.google.com/speech/reference/rest/v1beta1/speech/asyncrecognize#authorization,我正在尝试将包含以下信息的帖子请求发送到正文中的https://speech.googleapis.com/v1beta1/speech:asyncrecognize

public async Task<string> authLogin(string username, string password)
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri("http://172.20.129.193/");

        string jsonData = @"{""AdminNo"" : """+username+""", """+password+""" : ""password""}";

        var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
        HttpResponseMessage response = await client.PostAsync("NYPStudentLifeService/api/student/login",content);

        string result = await response.Content.ReadAsStringAsync();
        return result;
    }

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

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

1 个答案:

答案 0 :(得分: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. 手动构建字符串
  3. 使用Json.Net库来构建它。
  4. 对于audio.content字段,您需要将文件转换为base64字符串

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