Click here to Skip to main content
15,887,596 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 333.6K   23.7K   94  
Some steps for consuming a Json web service from a C# application
using System;
using System.Net;
using System.Windows.Forms;
using System.Runtime.Serialization.Json;

namespace Panoramio
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //fill the combo with the availbale sizes
            cmbSize.Items.Clear();
            foreach (PhotoSize size in Enum.GetValues(typeof(PhotoSize)))
            {
                cmbSize.Items.Add(size);
            }
            cmbSize.Text = PhotoSize.thumbnail.ToString();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                string url = GetURL();
                WebRequest request = WebRequest.Create(url);
                WebResponse ws = request.GetResponse();

                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(PanoramioData));
                PanoramioData photos = (PanoramioData)jsonSerializer.ReadObject(ws.GetResponseStream());
                
                Form2 form2 = new Form2();
                form2.Init(photos, txtGeonamesUser.Text);
                form2.Show();
            }
            catch (WebException wex)
            {
                //exceptions from the server are communicated with a 4xx status code
                HandleWebException(wex);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "BUG!");
            }
        }

        private void btnJavaScriptSerializer_Click(object sender, EventArgs e)
        {
            try
            {
                string url = GetURL();
                WebRequest request = WebRequest.Create(url);
                WebResponse ws = request.GetResponse();

                string jsonString = string.Empty;
                using (System.IO.StreamReader sreader = new System.IO.StreamReader(ws.GetResponseStream()))
                {
                    jsonString = sreader.ReadToEnd();
                }
                System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                PanoramioData photos = jsSerializer.Deserialize<PanoramioData>(jsonString);

                Form2 form2 = new Form2();
                form2.Init(photos, txtGeonamesUser.Text);
                form2.Show();
            }
            catch (WebException wex)
            {
                //exceptions from the server are communicated with a 4xx status code
                HandleWebException(wex);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "BUG!");
            }
        }

        private string GetURL()
        {
            //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
            string baseURL = "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}";
            string settype = txtUserID.Text;
            if (rbtAll.Checked)
                settype = "full";
            else if (rbtPublic.Checked)
                settype = "public";
            string url = string.Format(baseURL, txtResultMin.Text, txtResultMax.Text, txtMinX.Text, txtMaxX.Text, txtMinY.Text, txtMaxY.Text, cmbSize.Text, chkMapFilter.Checked, settype);
            return url;
        }

        private void HandleWebException(WebException wex)
        {
            string msg = "The server did not like your request.";
            HttpWebResponse hwr = wex.Response as HttpWebResponse;
            if (hwr != null)
            {
                msg += string.Format("\r\nThe status code is {0}, the status message: {1}.", (int)hwr.StatusCode, hwr.StatusDescription);
                using (System.IO.StreamReader sreader = new System.IO.StreamReader(hwr.GetResponseStream()))
                {
                    string errorMessage = sreader.ReadToEnd();
                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        msg += "\r\n\r\nThe further data sent from the server are:\r\n" + errorMessage;
                    }
                }
            }
            MessageBox.Show(msg, "Bad Request!");
        }
    }
}

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