简体   繁体   中英

consuming REST API with C#

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();
        }
    }
}

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;
}

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

What you are looking for is the WebClient class. It has a rich set of methods to do most HTTP related tasks, link to the full documentation below

WebClient MSDN

You need to read the response:

var stream = response.GetResponseStream();

Thenyou have your stream and do what you need with it. GetResponseStream

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM