[英]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.