[英]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的规定 ,我正在尝试将包含以下信息的发帖请求发送到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字符串,您可以:
对于audio.content字段,您需要将文件转换为base64字符串
Public Function ConvertFileToBase64(ByVal fileName As String) As String
Return Convert.ToBase64String(System.IO.File.ReadAllBytes(fileName))
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.