Currently trying to convert a curl command to Unity Web request
Curl Command:
curl -H “x-app-key:APP_KEY_HERE“ /
-F " file=@AudioFile.wav" /
-F "user_token=USER_TOKEN_HERE" /
-F "category=orange" /
https://api.soapboxlabs.com/v1/speech/verification
And the code I've attempted:
private string url = "https://api.soapboxlabs.com/v1/speech/verification";
private string apiKey = "123456789";
void Start()
{
StartCoroutine(MakeSoapboxRequest());
}
IEnumerator MakeSoapboxRequest()
{
List<IMultipartFormSection> form = new List<IMultipartFormSection> {
new MultipartFormFileSection("file", "Assets\\Pilot1\\Audio\\soapbox_test.wav"),
new MultipartFormDataSection("user_token", "aaa1234567"),
new MultipartFormDataSection("category", "orange")
};
UnityWebRequest request = UnityWebRequest.Post(url, form);
request.SetRequestHeader("x-app-key", apiKey);
yield return request.SendWebRequest();
if(request.isNetworkError || request.isHttpError)
{
Debug.LogError(request.error);
}
else
{
Debug.Log("No soapbox error");
Debug.Log(request.downloadHandler.text);
}
}
Keep getting an error HTTP/1.1.400 Bad request
As you can see I've tried and commented out, WWW form as well. Is it something to do with me sending the wav file? I've tried looking into sending it as bytes but was left confused. The API I'm sending it to only takes wav files. It returns a JSON file. I'm just using the downloadHandler.text as a test.
Any help would be appreciated. I haven't used CURL before and it's my first time trying Unity Web Requests.
Note that the overload you are using for the file is MultiPartFormFileSection(string data, string fileName)
and states
data: Contents of the file to upload.
fileName: Name of the file uploaded by this form section.
So what happens here is: You are trying to upload "file" as the file content in an anonymous file section.
I think you should rather get the actual byte[] and rather use the overload MultipartFormFileSection(string name, byte[] data, string fileName, string contentType)
name Name of this form section.
data Raw contents of the file to upload.
fileName Name of the file uploaded by this form section.
contentType The value for this section's Content-Type header.
e e.g. like
// Of course you would probably do these async before running the routine to avoid freeze
string yourFilePath;
var bytes = File.ReadAllBytes(yourFilePath);
new MultipartFormFileSection("file", bytes, "soapbox_test.wav", "application/octet-stream")
Finally note:
While a path like your given Assets\Pilot1\Audio\soapbox_test.wav might or might not work in the Unity Editor it will definitely fail in a build application!
You should either put your file into the StreamingAssets folder and access it via
var filePath = Path.Combine(Application.streamingAssetsPath, "fileName.extension");
or use the PersistentDataPath (you would of course have to make sure your file is stored there first)
var filePath = Path.Combine(Application.persistentDataPath, "fileName.extension");