Click here to Skip to main content
15,887,917 members
Articles / Programming Languages / C#
Tip/Trick

Class Library that uses HttpWebRequest and HttpWebResponse with JSON.Net and XML Serialization

Rate me:
Please Sign up or sign in to vote.
4.80/5 (6 votes)
22 Oct 2014CPOL2 min read 31K   693   17   2
This class is useful for HTTP web request and gets the response from the server. If the response is JSON or XML, this class also contains a method to parse or deserialize the response.

Introduction

The .NET Framework uses specific classes to provide information required to access Internet resources through a request/response. It also has classes to parse or deserialize the response. To make this short and easy to use, this class library helps us developers to request and get the response and to understand more on how to use HttpWebRequest, HttpWebResponse, JSON.Net and XML Serialization by checking the source code.

Using the Code

Download the attached DLL files and open a new Visual Studio project, add Reference and browse the downloaded attach files or copy and paste the class files HttpRequestResponse.cs and HttpWebBase.cs to your project and import the below namespace:

C++
using HttpWebRequestResponse;

HttpRequestResponse Class

Properties

  • GetServerResponse - Gets the final response from the server.
  • GetXmlResponseAsXDocument - If the response from server is XML, gets the response as XDocument
  • HTTP_CONTENT_TYPE - Sets the WebRequest Content Type (default: "application/x-www-form-urlencoded" )
  • HTTP_REQUEST_URI - Sets the WebRequest URI
  • PostRequestString - Sets the WebRequest string Buffer
  • USERNAME_HTTP - Sets the WebRequest Credentials Username
  • PASSWORD_HTTP - Sets the basic WebRequest Credentials Password
  • PROXY_SERVER - Sets the WebProxy Server Address
  • PROXY_PORT - Sets the WebProxy Server Port
  • HTTP_REQUEST_METHOD - Sets the WebRequest Method
  • HTTP_REQUEST_DATE - Sets the WebRequest Date
  • REQUEST_ENCODING - Sets the WebRequest Request encoding type (default: UTF8)

Methods

  • AddRequestHeader(string Name, object Value) - Sets the collection of header name/value pairs associated with the request.
  • WriteResponseToDrive(string Path, string FileName) - Writes the server response to text file

For JSON Response

  • DeserializeJsonResponseAsDataSet() - Deserializes JSON response into DataSet
  • DeserializeJsonResponseAsDataTable() - Deserializes JSON response into DataTable
  • DeserializeJsonResponseAsObject<T>() - Deserializes JSON into Object
  • ParseJsonElementResponseAsString(string Element) - Returns parse JSON response from server as string
  • ParseJsonResponseAsDictionary(object[] ListSearchKey) - Parses the JSON response base on the array parameter and return Dictionary

For XML response

  • ParseXmlResponseAsString(string Element) - Returns parse XML response from server element as string
  • DeserializeXmlResponseAsObject<T>() - Deserializes XML into Object
  • ParseXmlResponseAsDictionary(object[] ListSearchKey) - Parses XML response based on the Array key object.

Examples

The first code below illustrates how to request and get the response from server:

C++
static void Main(string[] args)
       {
           string URi = @"http://localhost:4444/api/user/get_user_info?login_name=Jel";
           using (HttpRequestResponse HttpWeb = new HttpRequestResponse(URi))
           {
               HttpWeb.HTTP_REQUEST_METHOD = "GET";
               HttpWeb.AddRequestHeader("Authorization", "SAMPLESIGNATURE");
               Console.WriteLine(HttpWeb.GetServerResponse); // Get the response from server
               Console.ReadLine();
           }
       }

Working with JSON response from server using ParseJsonResponseAsDictionary method:

C++
// *** Sample JSON response from Server ***
// {"error_code":"OK","message":"Successful"}

static void Main(string[] args)
        {            
            string URi = 
            @"http://localhost:4444/api/authentication/check_token?
            login_name=Jel&session_token=3fba2165c23e45519b4903cd310f65d7";         
            using (HttpRequestResponse HttpWeb = new HttpRequestResponse(URi))
            {
                Dictionary<object, object> oDictionary = new Dictionary<object, object>();
                HttpWeb.HTTP_REQUEST_METHOD = "GET";
                HttpWeb.AddRequestHeader("Authorization", "SAMPLESIGNATURE");
                object[] ListToParse = new object[] 
                { "error_code", "message" };
                oDictionary = HttpWeb.ParseJsonResponseAsDictionary
                    (ListToParse); // execute ParseJsonResponseAsDictionary method
                Console.WriteLine(oDictionary["error_code"]);
                Console.WriteLine(oDictionary["message"]);
                Console.ReadLine();     
            }
        } 

// *** Output ***
// OK
// Successful  

Working with JSON response from server using DeserializeJsonResponseAsDataTable method:

C++
// *** Sample JSON response from Server ***
// [{"error_code":"OK","message":"Successful","Name":"Jel", 
// "Lastname":"TheLastName"}]

static void Main(string[] args)
        { 
            string URi = @"http://localhost:4444/api/user/get_user_info?login_name=Jel";
            using (HttpRequestResponse HttpWeb = new HttpRequestResponse(URi))
            {
                DataTable oTable = new DataTable();
                HttpWeb.HTTP_REQUEST_METHOD = "GET";
                HttpWeb.AddRequestHeader("Authorization", "SAMPLESIGNATURE"));
                oTable = HttpWeb.DeserializeJsonResponseAsDataTable();
                DataRow oRow = oTable.Rows[0];
                foreach(var item in oRow.ItemArray)
                {
                    Console.WriteLine(item);
                }
                Console.ReadLine();     
            }
        } 

// *** Output ***
// OK
// Successful
// Jel
// TheLastName

Working with XMLresponse from server using DeserializeXmlResponseAsObject<T> method:

C++
// *** Sample XML response from Server ***
//  <?xml version="1.0" encoding="utf-8"?>
//  <Member>
//  <MemberCode>Jelo123</MemberCode>
//  <AccountID>1234ID</AccountID>
//  <CountryCode>PH</CountryCode>
//  </Member>

 class Program
    {
        static void Main(string[] args)
        {              
            string URi = @"http://localhost:3744/WebService.asmx/GetInfo"; 
            using (HttpRequestResponse HttpWeb = new HttpRequestResponse(URi))
            {                
                HttpWeb.HTTP_REQUEST_METHOD = "POST";
                HttpWeb.PostRequestBuffer = "MemberName=Jelo";
                var oMember = HttpWeb.DeserializeXmlResponseAsObject<Member>();
                Console.WriteLine(oMember.MemberCode);
                Console.WriteLine(oMember.AccountID);
                Console.WriteLine(oMember.CountryCode);    
                Console.ReadLine();     
            }
        }   
    }

    public class Member
    {
        public string MemberCode { get; set; }
        public string AccountID { get; set; }
        public string CountryCode { get; set; }    
    }

     
// *** Output ***
// Jelo123
// 123ID
// PH

License

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


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

Comments and Discussions

 
AnswerMy vote of 5 Pin
smoinard24-Oct-14 23:39
professionalsmoinard24-Oct-14 23:39 
GeneralMy Vote 5 Pin
Shemeemsha (ഷെമീംഷ)23-Oct-14 4:36
Shemeemsha (ഷെമീംഷ)23-Oct-14 4:36 
Nice Tip

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.