Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6320713
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T16:01:31+00:00 2026-05-24T16:01:31+00:00

I found an example about HTTP POST in msdn, but I am wondering how

  • 0

I found an example about HTTP POST in msdn, but I am wondering how can I make use of reactive extensions here.

using System;
 using System.Net;
 using System.IO;
 using System.Text; using System.Threading;

class HttpWebRequestBeginGetRequest
 {
     private static ManualResetEvent allDone = new ManualResetEvent(false);

    public static void Main(string[] args)
     {


        // Create a new HttpWebRequest object.
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/example.aspx");

        request.ContentType = "application/x-www-form-urlencoded";

        // Set the Method property to 'POST' to post data to the URI.
         request.Method = "POST";

        // start the asynchronous operation
         request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);

        // Keep the main thread from continuing while the asynchronous
         // operation completes. A real world application
         // could do something useful such as updating its user interface. 
        allDone.WaitOne();
     }

    private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
     {
         HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

        // End the operation
         Stream postStream = request.EndGetRequestStream(asynchronousResult);

        Console.WriteLine("Please enter the input data to be posted:");
         string postData = Console.ReadLine();

        // Convert the string into a byte array.
         byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        // Write to the request stream.
         postStream.Write(byteArray, 0, postData.Length);
         postStream.Close();

        // Start the asynchronous operation to get the response
         request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
     }

    private static void GetResponseCallback(IAsyncResult asynchronousResult)
     {
         HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

        // End the operation
         HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
         Stream streamResponse = response.GetResponseStream();
         StreamReader streamRead = new StreamReader(streamResponse);
         string responseString = streamRead.ReadToEnd();
         Console.WriteLine(responseString);
         // Close the stream object
         streamResponse.Close();
         streamRead.Close();

        // Release the HttpWebResponse
         response.Close();
         allDone.Set();
     }
 }

I am trying to use the following code, but it does not work. Can anyone help me out on this?
Thanks in advance -Peng

    return (from request in
                Observable.Return((HttpWebRequest)WebRequest.Create(new Uri(postUrl))).Catch(Observable.Empty<HttpWebRequest>())
                .Do(req =>
                        {
                            // Set up the request properties
                            req.Method = "POST";
                            req.ContentType = contentType;
                            req.UserAgent = userAgent;
                            req.CookieContainer = new CookieContainer();
                            Observable.FromAsyncPattern<Stream>(req.BeginGetRequestStream, req.EndGetRequestStream)()
                                .ObserveOnDispatcher()
                                .Subscribe(stream =>
                                        {
                                            stream.Write(formData, 0,
                                                         formData.Length);
                                            stream.Close();

                                        })
                                ;

                        })
            from response in
                Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse)().Catch(Observable.Empty<WebResponse>())
            from item in GetPostResponse(response.GetResponseStream()).ToObservable().Catch(Observable.Empty<string>())
            select item).ObserveOnDispatcher();

Edit: To make it clear, I want to use the rx to implement the same logic in MSDN example.
in the MSDN example, it seems it first makes async call to write RequestStream, and then in the GetRequestStreamCallback, fires another async call to get the response.
Using Rx, I am able to create 2 observables
1. Observable.FromAsyncPattern(request.BeginGetRequestStream, request.EndGetRequestStream)()
2. Observable.FromAsyncPattern(request.BeginGetResponse, request.EndGetResponse)()
The problem is the second observable depends on the first one’s result, so how can I do this in Rx?
In the first observable’s subcribe method to create the seond observable? is it the good way?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T16:01:31+00:00Added an answer on May 24, 2026 at 4:01 pm

    This is how I am doing it. I configure the two Async patters up front, then use SelectMany to chain them together.
    I have cut out the error handling etc from this code to keep it simple and show only the bare minimum to get it working. You should append a .Catch() similar to your own code, and if you want to get more than just a string out (say the response code) then you’ll need to create a class/struct to hold all the bits of data you need and return that instead.

    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;
      });
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

originally i was using a .net sdk for facebook found here: http://facebooktoolkit.codeplex.com/ but now,
I'm playing with the incomplete example found at http://www.w3.org/TR/offline-webapps/ But I'm distressed to see
How can I use WIA and Twain in C#? The TWIAIN/C# example found at
I'm trying to rewrite urls from the form: https://example.com/about to the form http://example.com/about using
I found an example for async ftp upload on msdn which does the following
I follow by entity framework example : http://msdn.microsoft.com/en-us/library/bb399182.aspx and I have problem with Identity
(I searched, and found lots of questions about converting relative to absolute urls, but
I found and followed an example from Stackoverflow (http://stackoverflow.com/questions/2310139/how-to-read-xml-response-from-a-url-in-java) of how to read an
I found an example of implementing the repository pattern in NHibernate on the web,
I found an example in the VS2008 Examples for Dynamic LINQ that allows you

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.