11

How to call REST API from a console application?

The response from my REST service will be XML format.

In web I am calling like this

string url = string.Format("{0}/name?PrimaryName={1}", ConfigurationManager.AppSettings["URLREST"], txtName.Text);
string details= CallRestMethod(url);

public string CallRestMethod(string url)
{                        
    HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);            
    webrequest.Method = "GET";           
    webrequest.ContentType = "application/x-www-form-urlencoded";
    webrequest.Headers.Add("Username", "xyz");
    webrequest.Headers.Add("Password", "abc");            
    HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();            
    Encoding enc = System.Text.Encoding.GetEncoding("utf-8");            
    StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);   
    string result = string.Empty;         
    result = responseStream.ReadToEnd();            
    loResponseStream.Close();           
    webresponse.Close();
    return result;
}

I want to call the same method in console application.

How can I do that?

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
JIKKU
  • 577
  • 4
  • 9
  • 26
  • 6
    What is stopping you from doing exactly that in a console application? `HttpWebRequest` resides in the System assembly, not in the System.Web assembly. – Maarten Mar 25 '14 at 06:54
  • 1
    @JIKKU I don't know why you cant use same code in console. please explain more. – sandeep Mar 25 '14 at 07:03

2 Answers2

29

Try this code class Program name space should be

using System.Net;
using System.IO;
{
    static void Main(string[] args)
    {
        string url = string.Format("{0}/name?PrimaryName={1}", System.Configuration.ConfigurationManager.AppSettings["URLREST"], "yournmae");
        string details = CallRestMethod(url);
    }

    public static string CallRestMethod(string url)
    {
        HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
        webrequest.Method = "GET";
        webrequest.ContentType = "application/x-www-form-urlencoded";
        webrequest.Headers.Add("Username", "xyz");
        webrequest.Headers.Add("Password", "abc");
        HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
        Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader responseStream = new StreamReader(webresponse.GetResponseStream(), enc);
        string result = string.Empty;
        result = responseStream.ReadToEnd();            
        webresponse.Close();
        return result;
    }
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Shyam sundar shah
  • 2,473
  • 1
  • 25
  • 40
  • Hi, is it possible to just omit all the stream stuff and just get the response body from this line: `HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();` If not, what is the point of this line of code... –  Jan 29 '18 at 21:46
1
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Net.Http.Formatting;

namespace TestingRESTAPI
{
    class Program
    {
        static void Main(string[] args)
        {
            RunAsync().Wait();
        }

        static async Task RunAsync()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("<<provide your uri>>");
                //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth","xyz");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                Console.WriteLine("Get");
                HttpResponseMessage response = await client.GetAsync("<<provide your uri>>");
                if(response.IsSuccessStatusCode)
                {
                    Sites sites = await response.Content.ReadAsAsync<Sites>();
                    Console.WriteLine("Name: " + sites.name + "," + "Year: " + sites.yearInscribed);
                }

                Console.WriteLine("Post");

                Sites newsite = new Sites();
                newsite.name = "Ryan";
                newsite.yearInscribed = "2019";
                response = await client.PostAsJsonAsync("api/sites", newsite);
                if(response.IsSuccessStatusCode)
                {
                    Uri siteUrl = response.Headers.Location;
                    Console.WriteLine(siteUrl);
                }

            }
        }
    }
}