Click here to Skip to main content
15,896,285 members
Articles / Web Development

Consuming a Json WebService from a C# or VB Application

Rate me:
Please Sign up or sign in to vote.
4.81/5 (26 votes)
2 Apr 2012CPOL7 min read 334K   23.7K   94  
Some steps for consuming a Json web service from a C# application
Imports System.Net
Imports System.Runtime.Serialization.Json
Imports System.Web.Script.Serialization

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-US")
        'fill the combo with the availbale sizes
        cmbSize.Items.Clear()
        For Each Size As PhotoSize In [Enum].GetValues(GetType(PhotoSize))
            cmbSize.Items.Add(Size)
        Next
        cmbSize.Text = PhotoSize.thumbnail.ToString()
    End Sub

    Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
        Try
            Dim url As String = GetURL()
            Dim request As WebRequest = WebRequest.Create(url)
            Dim ws As WebResponse = request.GetResponse()

            Dim jsonSerializer As DataContractJsonSerializer = New DataContractJsonSerializer(GetType(PanoramioData))
            Dim photos As PanoramioData = CType(jsonSerializer.ReadObject(ws.GetResponseStream()), PanoramioData)

            Dim form2 As Form2 = New Form2()
            form2.Init(photos, txtGeonamesUser.Text)
            form2.Show()
        Catch wex As WebException
            'exceptions from the server are communicated with a 4xx status code
            HandleWebException(wex)
        Catch ex As Exception
            MessageBox.Show(ex.ToString(), "BUG!")
        End Try
    End Sub

    Private Function GetURL() As String
        'http://www.panoramio.com/map/get_panoramas.php?set=public&from=0&to=20&minx=-180&miny=-90&maxx=180&maxy=90&size=medium&mapfilter=true
        Dim baseURL As String = "http://www.panoramio.com/map/get_panoramas.php?set={8}&from={0}&to={1}&minx={2}&miny={4}&maxx={3}&maxy={5}&size={6}&mapfilter={7}"
        Dim settype As String = txtUserID.Text
        If rbtAll.Checked Then
            settype = "full"
        ElseIf rbtPublic.Checked Then
            settype = "public"
        End If
        Dim url As String = String.Format(baseURL, txtResultMin.Text, txtResultMax.Text, txtMinX.Text, txtMaxX.Text, txtMinY.Text, txtMaxY.Text, cmbSize.Text, chkMapFilter.Checked, settype)
        Return url

    End Function

    Private Sub HandleWebException(ByVal wex As WebException)
        Dim msg As String = "The server did not like your request."
        Dim hwr As HttpWebResponse = CType(wex.Response, HttpWebResponse)
        If hwr IsNot Nothing Then
            msg += vbCrLf + String.Format("The status code is {0}, the status message: {1}.", hwr.StatusCode, hwr.StatusDescription)
            Using sreader As System.IO.StreamReader = New System.IO.StreamReader(hwr.GetResponseStream())
                Dim errorMessage As String = sreader.ReadToEnd()
                If Not String.IsNullOrEmpty(errorMessage) Then
                    msg += vbCrLf + vbCrLf + "The further data sent from the server are:" + vbCrLf + errorMessage
                End If
            End Using
        End If
        MessageBox.Show(msg, "Bad Request!")
    End Sub

    Private Sub btnJavaScriptSerializer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnJavaScriptSerializer.Click
        Try
            Dim url As String = GetURL()
            Dim request As WebRequest = WebRequest.Create(url)
            Dim ws As WebResponse = request.GetResponse()

            Dim jsonString As String = String.Empty
            Using sreader As System.IO.StreamReader = New System.IO.StreamReader(ws.GetResponseStream())
                jsonString = sreader.ReadToEnd()
            End Using

            Dim jsSerializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
            Dim photos As PanoramioData = jsSerializer.Deserialize(Of PanoramioData)(jsonString)

            Dim form2 As Form2 = New Form2()
            form2.Init(photos, txtGeonamesUser.Text)
            form2.Show()
        Catch wex As WebException
            'exceptions from the server are communicated with a 4xx status code
            HandleWebException(wex)
        Catch ex As Exception
            MessageBox.Show(ex.ToString(), "BUG!")
        End Try
    End Sub
End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions