Fishing some new slices of life…

Need some ReST ? Get a Hammock!

Hello dear techie friends!

Lately, I’ve been working quite a lot on Windows Phone 7 C# programming, and particularly on ReST requests (if you don’t know what a ReST request is, I suggest you simply check it here, seems a nice site for me). And I’ve discovered this pretty nice ReST library, Hammock, pretty useful to simplify this protocol, and quite valuable for WP7 programming. Thing is… data is quite hard to find about it, so I thought I would write a little something to help the community. And this will be my first comp-sci post… Therefore, here I am!

  • Include everything needed :
using Hammock;
using Hammock.Authentication;
using Hammock.Authentication.Basic;
using Hammock.Web;
  • Create a RestClient instance :
RestClient client = new RestClient
{
Authority = "http://www.google.fr",
SilverlightMethodHeader = "GET",
UserAgent = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0)" +
"(compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"
};

If you need credentials, create a corresponding object :

IWebCredentials credentials = (IWebCredentials)new BasicAuthCredentials
{
Username = "username",
Password = "password"
};

and then add it in the RestClient declaration :

RestClient client = new RestClient
{
Authority = "http://www.google.fr",
SilverlightMethodHeader = "GET",
Credentials = credentials,
UserAgent = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0)" +
"(compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"
};

If you’re behind an proxy requiring authentication (at work for instance), you will need this :

string authentication = "username:password";
string encodedAuth = System.Convert.ToBase64String(Encoding.UTF8.GetBytes(authentication));
client.AddHeader("Proxy-Authorization", "Basic " + encodedAuth);
  • Create a RestRequest instance :
RestRequest request = new RestRequest();
  • Throw the request and catch it with a callback function :
client.BeginRequest(request, new RestCallback(myCallback));

The callback function would be :

public void myCallback(RestRequest request, RestResponse response, object userState)
{
// Putting the response string into the variable named "hello".
string hello = response.Content;
}

Hope it helped people with Hammock!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s