Click here to Skip to main content
15,895,746 members

Response to: Windows Phone 8 Webrequest with https and custom header using Get

Revision 1
Hi =)
*First of all you must deal with Async pattern more carefully !!
* Coding the way like you did , how correct to say - is old school ;)
However , let's fix your problem,i'm going to resolve it with help of third-party tool called Rx (Reactive extension for WP).

So, let's define few helper methods :

C#
public static IObservable ToResponse(this WebRequest request)
{
    var asyncGetResponse = Observable.FromAsyncPattern(
                            request.BeginGetResponse, request.EndGetResponse);

    return Observable.Defer(asyncGetResponse);
}


C#
public static IObservable ToBytes(this Stream stream)
{
    return
        Observable.Create(
            observer =>
            {
                byte[] buffer = new byte[24];

                var obsReadFactory = Observable.Defer(() => stream.AsReader()(buffer, 0, buffer.Length));

                return Observable
                         .Repeat(obsReadFactory)
                         .Select(i => buffer.Take(i).ToArray())

                         // Subscribe on the thread pool, otherwise the repeat operator will operate during the
                         // call to subscribe, preventing the whole expression to complete properly
                         .SubscribeOn(Scheduler.ThreadPool)

                         .Subscribe(
                             _ =>
                             {
                                 if (_.Length > 0)
                                 {
                                     observer.OnNext(_);
                                 }
                                 else
                                 {
                                     observer.OnCompleted();
                                 }
                             },
                             observer.OnError,
                             observer.OnCompleted
                         );
            }
        );
}


And the last thing that remain , is to deal with WebRequest and proper request for it

C#
string url = _devApiUrl + "session/" + _entityKey;
var webRequest = WebRequest.Create(url);

webRequest.ToResponse()
          .SelectMany(wr => wr.GetResponseStream().ToBytes())
          .ForEach(b => {
                  //Do some stuff with bytes for example get strings 
                  string data=  Encoding.Default.GetString(b);
                  }));
Posted 26-Dec-12 11:11am by Oleksandr Kulchytskyi.