2014-03-25 96 views
3

如何從控制檯應用程序調用REST API?如何從控制檯應用程序調用REST API?

來自我的REST服務的響應將是XML格式。

在網上我打電話這樣

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

我想打電話給在控制檯應用程序的方法相同。

我該怎麼做?

+4

取之於正是在做一個控制檯應用程序阻止你? 'HttpWebRequest'駐留在System程序集中,而不是System.Web程序集中。 – Maarten

+0

@JIKKU我不知道你爲什麼不能在控制檯中使用相同的代碼。請詳細解釋。 – sandeep

+0

好的,它工作正常 – JIKKU

回答

12

試試這個代碼類節目 名字空間應該是

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

謝謝你的幫助! – LuckyS

+0

嗨,是否有可能只是省略所有的流的東西,只是從這一行得到響應正文: 'HttpWebResponse webresponse =(HttpWebResponse)webrequest.GetResponse();' 如果不是,這條線的重點是什麼的代碼... – KeplerIO