2009-05-23 44 views
0

我需要與傳統的php應用程序進行通信。該API只是一個PHP腳本,而不是接受獲取請求並將響應作爲XML返回。如何通過C#中的僞REST服務觸發GET請求#

我想用C#編寫通信。

什麼是最佳的方法來觸發GET請求(有很多參數),然後解析結果?

理想情況下,我想找到的東西,很容易爲下面的Python代碼:

params = urllib.urlencode({ 
    'action': 'save', 
    'note': note, 
    'user': user, 
    'passwd': passwd, 
}) 

content = urllib.urlopen('%s?%s' % (theService,params)).read() 
data = ElementTree.fromstring(content) 
... 

UPDATE: 我在考慮使用XElement.Load,但我不明白的方式來輕鬆構建GET查詢。

回答

1

WCF REST Starter Kit中有一些很好的實用程序類,用於實現調用在任何平臺中實現的服務的.NET REST客戶端。

Here's a video介紹瞭如何使用客戶端件。

示例代碼片段:

HttpClient c = new HttpClient("http://twitter.com/statuses"); 
c.TransportSettings.Credentials = 
    new NetworkCredentials(username, password); 
// make a GET request on the resource. 
HttpResponseMessage resp = c.Get("public_timeline.xml"); 
// There are also Methods on HttpClient for put, delete, head, etc 
resp.EnsureResponseIsSuccessful(); // throw if not success 
// read resp.Content as XElement 
resp.Content.ReadAsXElement(); 
0

簡單的System.Net.Webclient在功能上與pythonurllib相似。

C#的例子(略編輯形式以上裁判)示出了如何「火GET請求」:

using System; 
using System.Net; 
using System.IO; 
using System.Web; 

public class Test 
{ 
    public static String GetRequest (string theService, string[] params) 
    { 
     WebClient client = new WebClient(); 

     // Add a user agent header in case the 
     // requested URI contains a query. 

     client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); 

     string req = theService + "?"; 
     foreach(string p in params) 
      req += HttpUtility.UrlEncode(p) + "&"; 
     Stream data = client.OpenRead (req.Substring(0, req.Length-1) 
     StreamReader reader = new StreamReader (data); 
     return = reader.ReadToEnd(); 
    } 
} 

爲了解析結果,使用System.Xml類,或更好 - System.Xml.Linq類。直接的方法是XDocument.Load(TextReader)方法 - 您可以直接使用由OpenRead()返回的WebClient流。

+0

難道你不知道.NET更好網址構建器?您正在構建的網址無效。儘管你使用「?」而不是「&」你沒有逃過params。所以你可以很容易地結束截斷參數。 – 2009-05-23 12:15:27