2009-05-23 94 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