REST Web Services - Post and Get for WP7

by Danielvg 29. August 2011 21:51

I have been playing around with WP7 and Reactive Extensions for a few days, and wanted to share a RestRequest object for doing REST based web service post and get. The requests are done with HttpWebRequest  and support basic authentication.

Following is the main part of the RestRequest object, see the attachment for the complete implementation.

public IObservable<string> HttpGet(Uri uri, Action<HttpStatusCode, string> error, 
    Action<Exception> onException)
{
    ValidateStandardParameters(uri, error, onException);
    var result = new Subject<string>();

    var request = CreateRequest(uri, MethodType.Get);
    var requestAsync = Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse);
    requestAsync().Subscribe(respons =>
    {
        ResponseHandler(respons, result, error);
    }, onException);
    return result;
}

public IObservable<string> HttpPost(Uri uri, string postData, 
    Action<HttpStatusCode, string> error, Action<Exception> onException)
{
    ValidateStandardParameters(uri, error, onException);
    var result = new Subject<string>();

    var request = CreateRequest(uri, MethodType.Post);
    var requestAsync = Observable.FromAsyncPattern<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream);
    var responseAsync = Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse);

    requestAsync().SelectMany(requestStream =>
    {
        using (var writer = new StreamWriter(requestStream))
        {
            writer.Write(postData);
        }
        return responseAsync();
    }).Subscribe(response =>
    {
        ResponseHandler(response, result, error);
    }, onException);
    return result;
}

 

And to use it:

var uri = new Uri("https://www.somehost.dk/Users/1");
_restRequest.HttpGet(uri).Subscribe(s =>
    {
        using (var stream = new StringReader(s))
        {
            var serializer = new XmlSerializer(typeof(User));
            var user = (User)serializer.Deserialize(stream);
            // do something with user..
        }
    });

 

When I have a use case for it I will add support for additional headers and PUT/DELETE.

This is the first time I have worked with Reactive Extensions so I am sure there is room for improvements. Any feedback is appreciated!

RestRequest.cs (4,67 kb)