4

[UPDATE] Problem fixed. Working code and method updated below!

So, I am trying to post a comment to a SoundCloud track using the SoundCloud api in AS3. The documentation can be found here:

http://developers.soundcloud.com/docs/#comments

And my code is as follows:

            var urlLoader:URLLoader = new URLLoader();
            var urlString:String = "https://api.soundcloud.com/tracks/" + soundModel.currentlyPlayingItem.id + "/comments.json" + "?comment[body]=" + commentString + "&comment[timestamp]=" + trackPositionComment;  
            var urlRequest:URLRequest = new URLRequest(urlString);

            urlRequest.method = URLRequestMethod.POST;


            var variables:URLVariables = new URLVariables();
            variables.oauth_token = soundModel.userToken; //here is the filler variable to make POST, not GET.
            urlRequest.data = variables;

            urlRequest.contentType = "application/x-www-form-urlencoded";

            var header2:URLRequestHeader=new URLRequestHeader("oauth_token",soundModel.userToken);
            var header3:URLRequestHeader=new URLRequestHeader("client_id", "sdjhb4jhbkjbe4gkjbh4random");
            urlRequest.requestHeaders.push(header2);
            urlRequest.requestHeaders.push(header3);

            urlLoader.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, commentPosted);
            urlLoader.load(urlRequest);

Originally I was consistently getting a 401 - unauthorized error.

After playing around with the SoundCloud API console, I saw that there was a 'content-length' of 0, meaning no body. So all the authentication stuff had to be going in headers, not variables. However, with POST method in AS3 UrlLoader, it will automatically send as a GET if there is no body (variables) included. So for that reason I left an arbitrary variable value.

Also the two parameters, 'body' and 'timestamp' indeed have to be sent as 'comment[body]' and 'comment[timestamp]' even though this isn't quite made clear in the documentation. Also both of these parameters have to be included in the URL, and not as variables or headers.

Finally, to get a authorized return, you must provide both your 'client_id' and 'oauth_token' as headers.

It was this magic combination that did it for me. I hope this helps some other people, ready to rip their hair out like I was.

Thx, Theo M.

4

0 回答 0