Consume WCF REST Services using GET Operation and JSON based communication (with Windows Forms Client)

by Jagadish Pulakhandam on 2/7/2012 1:53:01 PM
Rated 0 from 0 votes
Brief: Demonstrates consuming a WCF REST service using a simple Windows Forms Client Application. Uses JSON for communication/data exchange.
Posted to: Consuming WCF REST Services
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

The sample demonstrates the following:
  • How to fetch data from WCF REST service using Windows Forms (using HTTP GET operations) with JSON communication
  • How to use WebRequest class to fetch from WCF REST service
  • How to use HttpWebRequest and HttpWebResponse to work with WCF REST service
  • Working 'Stream' object returned by HttpWebResponse
  • How to convert or deserialize JSON returned from a WCF REST service to a .NET custom object.
NOTE: The samples use JSON to communicate to WCF REST service.  If you need source code of WCF REST Service or XML based communication with WCF REST service, check out "Related Posts" section.

Screen shot:

Source code (in VB.NET) :

01.Imports System.Net
02.Imports System.IO
03.Imports System.Text
04.Imports System.Runtime.Serialization.Json
06.Public Class Form1
08.    Private Sub btnGetEmployeeDetails_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetEmployeeDetails.Click
09.        Dim uri As String = "http://localhost:8080/SampleEmpService/Employees/" & txtEmpno.Text
10.        Dim req As HttpWebRequest = WebRequest.Create(uri)
11.        Dim resp As HttpWebResponse = req.GetResponse()
12.        Dim respStream As Stream = resp.GetResponseStream()
14.        'Dim readStream As New StreamReader(respStream, Encoding.UTF8)
15.        'MessageBox.Show(readStream.ReadToEnd())
17.        Dim ser As New DataContractJsonSerializer(GetType(Employee))
18.        Dim oEmp As Employee = CType(ser.ReadObject(respStream), Employee)
19.        Me.lblEname.Text = oEmp.Ename
20.        Me.lblSal.Text = oEmp.Sal
21.        Me.lblDeptno.Text = oEmp.Deptno
23.        respStream.Close()
24.        resp.Close()
26.    End Sub
28.    Public Class Employee
29.        Public Empno As String
30.        Public Ename As String
31.        Public Sal As String
32.        Public Deptno As String
33.    End Class
35.End Class

Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following