Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

consuming REST API with C#

Tags:

rest

c#

http

I'm very new to C# and want to learn how to make HTTP requests. I want to start really simple, although that is currently evading me. I want to just perform a GET on, say, google.com. I created a command line application, and have this code. Not sure at all which usings are required.

I tested it by writing to the console, and it doesn't get past the response. Can somebody please clue me in? I'm looking to do some simple curl type stuff to test an existing API. Thank you for your help.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;

namespace APItest
{
    class testClass
    {
        static void Main(string[] args)
        {
            string url = "http://www.google.com";

            Console.WriteLine(url);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Console.ReadKey();
        }
    }
}
like image 506
allstar Avatar asked Mar 23 '23 06:03

allstar


2 Answers

I would look into using HttpClient instead which was created to make calling rest API's much easier in .net 4. It also supports async and await.

You can call it like this (using async):

async Task<HttpResponseMessage> GetGoogle() {

    HttpClient client = new HttpClient();

    Uri uri = new Uri("http://www.google.com");

    var result = await client.GetAsync(uri);

    return result;
}
like image 180
Daniel Little Avatar answered Apr 02 '23 19:04

Daniel Little


I would not recommend using HTTPWebRequest/HTTPWebResponse for consuming web services in .Net. RestSharp is much easier to use.

like image 44
Spencer Ruport Avatar answered Apr 02 '23 20:04

Spencer Ruport