.Net OAuth Sample – Working with Justin.TV
Posted by: Marker | Technical | 21.09.2009
This sample uses the excellent DevDefined OAuth .Net Implementation along with the Justin.TV rest apis for working with streaming and archived video.
Here’s some sample .net code to create a channel and user in justin.tv. The OAuthRequest wrapping class is then presented which acts as a core facade to justin.tv apis which secures the calls via a direct 2-legged request.
You should be able to modify the OAuthRequest and sample code for any OAuth based rest api as required.
Sample code to create new channel and user
// create new OAuthRequest and session
var oauthRequest = new OAuthRequest();
var oauthSession = oauthRequest.CreateSession();
// build up thepost request
oauthSession.WithFormParameters(
new
{
login = "[LOGIN]",
password = "[PASSWORD]",
birthday = "[DATEOFBIRTH]",
email = "[EMAIL]",
category = "[CATEGORY]",
subcategory = "[SUBCATEGORY]",
title = "[TITLE]",
publisher_guard = "[PUBLISHER_GUARD]"
}
);
// make the post request get the response as xml
HttpWebResponse results = oauthSession.Request().Post().ForUrl("http://api.justin.tv/api/channel/create.xml").ToWebResponse();
XDocument xdoc =oauthRequest.GetWebResponseAsXml(results);
// continue processing...
OAuthRequest facade class
using DevDefined.OAuth;
using DevDefined.OAuth.Consumer;
using DevDefined.OAuth.Framework;
using System.Xml;
using System.Xml.Linq;
using System.Net;
using System.IO;
using System.Text;
public class OAuthRequest
{
private string requestUrl = "http://api.justin.tv/oauth/request_token";
private string userAuthorizeUrl = "http://api.justin.tv/oauth/authorize";
private string accessUrl = "http://api.justin.tv/oauth/access_token";
public OAuthSession CreateSession()
{
var consumerContext = new OAuthConsumerContext
{
ConsumerKey = "YOURCONSUMERKEY",
ConsumerSecret = "YOURCONSUMERSECRET",
SignatureMethod = SignatureMethod.HmacSha1,
UseHeaderForOAuthParameters = true
};
var session = new OAuthSession(consumerContext, requestUrl, userAuthorizeUrl, accessUrl);
return session;
}
public XDocument GetWebResponseAsXml(HttpWebResponse response)
{
XmlReader xmlReader = XmlReader.Create(response.GetResponseStream());
XDocument xdoc = XDocument.Load(xmlReader);
xmlReader.Close();
return xdoc;
}
public string GetWebResponseAsString(HttpWebResponse response)
{
Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new
StreamReader(response.GetResponseStream(), enc);
return loResponseStream.ReadToEnd();
}
}
I recevied this mensage – (400) Bad Request. at System.Net.HttpWebRequest.GetResponse() -
what a heppening?
i am getting the error:
The remote server returned an error: (400) Bad Request.
Kindly suggest the solution.