15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

HTTP Client application ❘ 891<br />

hTTP ClienT aPPliCaTion<br />

The client application can be a simple application to just send HTTP requests to the service <strong>and</strong> receive<br />

AtomPub or JSON responses. The first client application example is a WPF application that makes use of<br />

the HttpWebRequest class from the System.Net namespace.<br />

Figure 32-2 shows the UI from the Visual Studio Designer. A TextBox named textUrl is used to enter the<br />

HTTP request with a default value of http://localhost:9000/Samples/Menus. The read-only TextBox<br />

named textReturn receives the answer from the service. You can also see a CheckBox checkJSON, where<br />

the response can be requested in the JSON format. The Button with the content Call Data Service has the<br />

Click event associated to the OnRequest() method.<br />

In the implementation of the OnRequest()<br />

h<strong>and</strong>ler, an HttpWebRequest object is created<br />

with the WebRequest.Create() factory method.<br />

The HTTP request that is sent is defined by<br />

the textUrl.Text property. If the JSON<br />

checkbox is selected, the Accept property of<br />

the HttpWebRequest is set to application/<br />

json. This way, the data service returns a<br />

JSON response instead of the default AtomPub<br />

format. The request to the server is sent with<br />

the asynchronous method BeginGetResponse.<br />

When a response from the service is received,<br />

the method defined with the first parameter<br />

as a Lambda expression is invoked. The<br />

response is read from a stream associated with<br />

HttpWebResponse, converted to a string, <strong>and</strong><br />

passed to the textResult TextBox.<br />

figure 32-2<br />

private void OnRequest(object sender, RoutedEventArgs e)<br />

{<br />

HttpWebRequest request = WebRequest.Create(textUrl.Text)<br />

as HttpWebRequest;<br />

if (checkJSON.IsChecked == true)<br />

{<br />

request.Accept = "application/json";<br />

}<br />

request.BeginGetResponse((ar) =><br />

{<br />

try<br />

{<br />

using (MemoryStream ms = new MemoryStream())<br />

{<br />

const int bufferSize = 1024;<br />

byte[] buffer = new byte[bufferSize];<br />

HttpWebResponse response =<br />

request.EndGetResponse(ar) as HttpWebResponse;<br />

Stream responseStream = response.GetResponseStream();<br />

int count;<br />

while ((count = responseStream.Read(buffer, 0,<br />

bufferSize)) > 0)<br />

{<br />

ms.Write(buffer, 0, count);<br />

}<br />

responseStream.Close();<br />

byte[] dataRead = ms.ToArray();<br />

string data = UnicodeEncoding.ASCII.GetString(<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!