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

查看:116
本文介绍了如何从控制台应用程序调用REST API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to call REST API from a console application?

REST服务的响应将为XML格式。

The response from my REST service will be XML format.

在网络中,我这样呼叫

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.

我该怎么做?

推荐答案

尝试此代码类程序
名称空间应使用System.Net

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

这篇关于如何从控制台应用程序调用REST API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆