2

I'm using this code snippet to send POST request:

public IObservable<string> BeginPost(Uri uri, string postData)
{
    var request = HttpWebRequest.CreateHttp(uri);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";

    var fetchRequestStream = Observable.FromAsyncPattern<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream);
    var fetchResponse = Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse);
    return fetchRequestStream().SelectMany(stream =>
    {
        using (var writer = new StreamWriter(stream)) writer.Write(postData);
        return fetchResponse();
    }).Select(result =>
    {
        var response = (HttpWebResponse)result;
        string s = "";
        if (response.StatusCode == HttpStatusCode.OK)
        {
            using (var reader = new StreamReader(response.GetResponseStream())) 
                s = reader.ReadToEnd();
        }
        return s;
    });
}

I'm new to C# and I don't really understand why do I have to use this IObservable interface. I was trying to find any information about it on the internet, but I couldn't.

What I really need is to get reponse from webservice as a string and in the example I gave, what I get is IObservable<string>. So basically, how can I get my string from it?

I know this is a bit silly question, but I would also appreciate any links to sites where I could read more about this.

4

1 回答 1

4

You do not have to use an IObservable. I suppose you got this code from someone working with Reactive Extensions. The idea behind this is, that you subscribe to this "event" and each time the request is made a string is send to you. For more info on Reactive Extensions, see the answers to this question Reactive Extension (Rx) tutorial that is up to date

If you do not want to use the Reactive Extensions, I recommend using RestSharp. It is a nice library that also works with Windows Phone and you can find many samples on how to use it.

于 2013-01-07T10:17:02.717 回答