Example of using HttpWebRequest and HttpWebResponse to send POST data

The code in Listings 14.12 and 14.13 shows an example Silverlight application that uses an HttpWebRequest object to send a POST request to a simple PHP Web service and uses an HttpWebResponse object to get the response and update the UI.

The code in Listing 14.12 defines a simple e-mail form that collects the To, From, Subject, and Message data in four TextBox controls: To, From, Subject, and Message. A Button control, SendBtn, is implemented to initiate the HttpWebRequest to send the data from the form as a POST request to the service. A TextBlock, StatusText, is defined to display the response from the request.

LISTING 14.12

Page.xaml File That Defines an E-mail Form That Is Used to Send E-mail Data to a Web Service Using an HttpWebRequest

<UserControl x:Class="WebRequestApp.Page"

xmlns="http://schemas.microsoft.com/client/2 0 07" xmlns:x="http://schemas.microsoft.com/winfx/2 00 6/xaml" Width="64 0" Height="4 00">

<Grid x:Name="LayoutRoot" Background="LightBlue"> <TextBlock Text="To:" Margin=M10,10<0<0M VerticalAlignment="Top" HorizontalAlignment=MLeftM /> <TextBox x:Name=MToM

VerticalAlignment="Top" HorizontalAlignment=MLeftM Margin=M10 0,10,0,0M Width=M2 00M/> <TextBlock Text="From:" Margin=M10,50,0,0M VerticalAlignment=MTopM HorizontalAlignment=MLeftM /> <TextBox x:Name=MFromM

VerticalAlignment=MTopM HorizontalAlignment=MLeftM Margin=M100,50,0,0M Width="200"/> <TextBlock Text=MSubject:M Margin=M10,90,0,0M VerticalAlignment=MTopM HorizontalAlignment="Left" /> <TextBox x:Name=MSubjectM

VerticalAlignment=MTopM HorizontalAlignment="Left" Margin=M100,90,0,0M Width=M5 00M/> <TextBlock Text=MMessage:M Margin=M10,130,0,0M VerticalAlignment=MTopM HorizontalAlignment=MLeftM /> <TextBox x:Name="Body"

VerticalAlignment=MTopM HorizontalAlignment=MLeftM Margin=M100,130,0,0M Height=M200M Width="500" AcceptsReturn=MTrueM /> <Button x:Name=MSendBtnM Content="Send" Height=M3 0M Width="100" VerticalAlignment=MBottomM Margin=M20M/> <TextBlock x:Name=MStatusTextM

VerticalAlignment=MBottomM Margin=M20M/>

The code in Listing 14.13 first implements the System.Net library for the HttpWebRequest and HttpWebResponse classes and the System.IO library for the Stream, StreamReader, and StreamWriter classes.

Inside the Page() constructor, the code attaches a Click event handler, DoRequest() , functions to the SendBtn control. Inside the DoRequest() function, the code creates an HttpRequest object, request, using the following line of code:

HttpWebRequest request =

(HttpWebRequest)HttpWebRequest.Create(new Uri(serviceUrl));

The Method property of the request is set to POST and the ContentType is set to application/x-form-urlencoded to define a POST request, as shown in the following line of code:

request.Method = "POST";

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

Because this is a POST request, the BeginGetRequestStream() function is called to get an IO stream to send the POST data on. The AsyncCallback handler requestHandler() is attached to handle the get request stream completed event.

Inside the requestHandler() function, the code first creates a POST data string from the UI form elements. Then it gets the request from the AsyncState of the IAsyncResult argument and uses the EndGetRequstStream() function of the request object to get the IO stream using the following lines of code:

HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState; Stream requestStream = request.EndGetRequestStream(asyncResult);

The POST data is written to the HttpWebRequest using a StringWriter object. The data is flushed to the stream and the stream is closed. After the data is written, the code uses the BeginGetResponse() function of the request object to send the request to the server. The AsyncCallback handler responseHandler() is attached to handle the get response completed event using the following line of code:

request.BeginGetResponse(new AsyncCallback(responseHandler),request);

Inside the responseHandler() function, the code gets the request from the AsyncState of the IAsyncResult argument and uses the EndGetResponse() function of the request object to get the HttpWebResponse object from the request.

The code checks the HaveResponse property of the request object to verify that there is a response and then checks the StatusCode property of the response object to verify that the service was successful. Then the code uses the GetResponseStream() function of the HttpWebResponse object to get the response stream and update the Text property of the StatusText control using the following code:

StreamReader reader =

new StreamReader(response.GetResponseStream()); StatusText.Text = reader.ReadToEnd();

The code then removes the SendBtn from the control so that the status of the request takes its place.

LISTING 14.13

Page.xaml.cs File That Implements an HttpWebRequest to Send a POST Request to a Remote Web Service using System;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Net; using System.IO;

namespace WebRequestApp {

public partial class Page : UserControl {

InitializeComponent();

SendBtn.Click += new RoutedEventHandler(DoRequest);

void DoRequest(object sender, RoutedEventArgs e) {

string serviceUrl =

"http://www.myserver.com/mailservice.php"; HttpWebRequest request =

(HttpWebRequest)HttpWebRequest.Create(new Uri(serviceUrl)); request.Method = "POST";

request.ContentType = "application/x-form-urlencoded"; request.BeginGetRequestStream(new AsyncCallback(requestHandler), request);

void requestHandler(IAsyncResult asyncResult)

continued

LISTING 14.13

(continued)

string postData =

String.Format("ToAddr={0}&FromAddr={1}&Subject={2}&Body={3}"/ To.Text, From.Text, Subject.Text, Body.Text);

HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState; Stream requestStream = request.EndGetRequestStream(asyncResult);

StreamWriter writer = new StreamWriter(requestStream);

writer.Write(postData);

writer.Flush();

writer.Close();

request.BeginGetResponse(new AsyncCallback(responseHandler), request);

void responseHandler(IAsyncResult asyncResult) {

HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState; HttpWebResponse response =

(HttpWebResponse)request.EndGetResponse(asyncResult); if (request.HaveResponse &&

response.StatusCode == HttpStatusCode.OK) {

StreamReader reader =

new StreamReader(response.GetResponseStream());

StatusText.Text = reader.ReadToEnd( reader.Close();

StatusText.Text = "No Response From Mail Server";

LayoutRoot.Children.Remove(SendBtn)

The results of the application defined by Listings 14.12 and 14.13 are shown in Figure 14.6. When the user clicks Send, an HttpWebRequest is initiated that gets data from a form and sends a POST request to a remote Web service to send the e-mail. The status of the request is displayed in the bottom of the form after the message is sent.

FIGURE 14.6

Silverlight application that collects e-mail data from a form and uses an HttpWebRequest to post the data to a remote Web service

FIGURE 14.6

Httpwebrequest
+1 -2

Average user rating: 2.3 stars out of 3 votes

Post a comment

  • Receive news updates via email from this site