简体   繁体   English

如何从控制台应用程序调用 REST API?

[英]How to call REST API from a console application?

How to call REST API from a console application?如何从控制台应用程序调用 REST API?

The response from my REST service will be XML format.我的 REST 服务的响应将是 XML 格式。

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?我怎样才能做到这一点?

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

            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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