I am trying to upload a file to SoundCloud with the WWW class. When i run the code below i get a response ‘400 Bad Request’. Can someone tell me why or give me some hints what to look for?
Is it even possible to use the WWW class for this?
EDIT:
I looked a bit with Fiddler. I get the following message when running the code:
‘Content-Length mismatch: Request Header indicated 208.662 bytes, but client sent 0 bytes.’
public IEnumerator UploadFileWebClient(FileInfo file)
{
byte[] fileContents = File.ReadAllBytes(file.FullName);
WWWForm form = new WWWForm();
form.AddField("track[title]", "Some title", System.Text.Encoding.UTF8);
form.AddField("track[sharing]", "private", System.Text.Encoding.UTF8);
form.AddField("oauth_token", soundCloudToken, System.Text.Encoding.UTF8);
form.AddField("format", "json", System.Text.Encoding.UTF8);
form.AddBinaryData("track[asset_data]", fileContents, "0.wav", "application/octet-stream");
foreach(var header in form.headers)
{
Debug.Log ("Header: " + header);
}
WWW download = new WWW("https://api.soundcloud.com/tracks", form);
yield return download;
if(!string.IsNullOrEmpty(download.error))
{
Debug.Log ( "Error downloading: " + download.error );
}
else
{
Debug.Log(download.text);
}
}
UPDATE: the SoundCloud token request (just for the completeness of the question):
public IEnumerator GetTokenAndUploadFile(MonoBehaviour mono, FileInfo file)
{
Debug.Log ( "GetTokenAndUploadFile() started");
ServicePointManager.ServerCertificateValidationCallback = (p1, p2, p3, p4) => true;
var form = new WWWForm ();
form.AddField ("client_id", _clientId);
form.AddField ("client_secret", _clientSecret);
form.AddField ("grant_type", "password");
form.AddField ("username", _username);
form.AddField ("password", _password);
//Authentication
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
Debug.Log ( "Try to get token");
WWW download = new WWW(soundCloudTokenRes, form);
yield return download;
if(!string.IsNullOrEmpty(download.error))
{
Debug.Log ( "Error downloading: " + download.error );
}
else
{
var tokenInfo = download.text;
tokenInfo = tokenInfo.Remove(0, tokenInfo.IndexOf("token\":\"") + 8);
soundCloudToken = tokenInfo.Remove(tokenInfo.IndexOf("\""));
Debug.Log(string.Format("Token set: {0}", soundCloudToken));
}
}