Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • HttpClient Class

    • 0
    • 2
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 67
    Comment on it

    HttpClient class is used to send the http request and receive http response by URL.
    It is defined inside the System.Net.Http namespace.
    HttpClient is instantiated  once and re-used throughout the life of an application.


    Properties:
    It contains a following properties:


    1. BaseAddress:- This property is used to get or set the base address of Uniform Resource Identifier (URI) of the Internet resource used while sending a request.
    2. DefaultRequestHeaders:- This property is used to get the header which is used to sent with each request.
    3. Timeout:- This property is used to get or set the number of milliseconds to wait before the request times out.

     

    We are assuming a class "Company"

    Code for class company:

    Class Company
    {
    int Id {get;set;} 
    string Company{get;set;}
    }
    

     

    To Initialize the HttpClient instance, See the below code

    HttpClient client = New HttpClient();
    client.BaseAddress = New Uri("http://localhost:52084/");
    client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
    

     

    To send the Get request, See the below code

    Company company=null;
     var url = "Service1.svc/GetCompanies";
     HttpResponseMessage response = client.GetAsync(url).Result;
    if (response.IsSuccessStatusCode) 
    {
       var myobject = response.Content.ReadAsStringAsync().Result;                    
    company= JsonConvert.DeserializeObject<Company>(myobject);
    }
    

     

    To send a Post request, See the below code

    Company company=new Company{ Company="ABCD" };
    var url = "Service1.svc/SaveCompany";
    var json = JsonConvert.SerializeObject(company);
    var companyString = New StringContent(json, Encoding.UTF8, "application/json");
    HttpResponseMessage response= client.PostAsync(url, companyString).Result;
    if (response.IsSuccessStatusCode) 
    {
      var myobject = response.Content.ReadAsStringAsync().Result;                  
      result = JsonConvert.DeserializeObject<Company>(myobject);
    }
    
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: