- Home /
Sending an HTTP POST request with JSON body
I am trying to get the Google Cloud Speech API to work in my Unity game. Unfortunately, I cannot install the Google Speech API into a script for my project as it is dependent on .NET 4.5 whereas Unity is using .NET 3.5 (and yes there is an experimental .NET 4.6 for Unity and I have used it with no success).
Therefore, I have resorted to having to send a POST HTTP request. I have successfully done so through the Google Cloud Shell, however, I need to somehow use Visual Studio to send the request with C#. I have looked at similar threads but haven't had much luck. I have installed RestSharp but have not found the documentation sufficient.
I need to:
POST https://speech.googleapis.com/v1/speech:recognize
with the following JSON body:
{
"config": {
"encoding":"FLAC",
"sample_rate": 16000,
"language_code": "en-US"
},
"audio": {
"uri":"gs://cloud-samples-tests/speech/brooklyn.flac"
}
}
I have tried for hours to get this seamingly simple task to work in Visual Studio so I can import it into the Unity Engine. How can I do this with JSON parameters?
Thanks
One of the countless duplicates of
https://answers.unity.com/questions/1163204/prevent-unitywebrequestpost-from-url-encoding-the.html
Answer by RMGK · Mar 13, 2019 at 11:49 PM
This is a tough one. The way I got around it was using a custom Uploader using UnityWebRequest. Something like below:
UnityWebRequest webRequest = new UnityWebRequest(<URL>, "POST");
byte[] encodedPayload = new System.Text.UTF8Encoding().GetBytes(<JSON PAYLOAD STRING>);
webRequest.uploadHandler = (UploadHandler) new UploadHandlerRaw(encodedPayload);
webRequest.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
webRequest.SetRequestHeader("Content-Type", "application/json");
webRequest.SetRequestHeader("cache-control", "no-cache");
UnityWebRequestAsyncOperation requestHandel = webRequest.SendWebRequest();
requestHandel.completed += delegate(AsyncOperation pOperation) {
Debug.Log(webRequest.responseCode);
Debug.Log(webRequest.downloadHandler.text);
};