我需要与传统的php应用程序进行通信。 API只是一个php脚本,而不是接受get请求并以XML格式返回响应。
我想用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)
...
更新 我正在考虑使用XElement.Load,但我没有看到轻松构建GET查询的方法。
答案 0 :(得分: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();
答案 1 :(得分:0)
简单的System.Net.Webclient
在功能上类似于python
的{{1}}。
urllib
示例(上面的参考资料稍加编辑)显示了如何“触发GET请求”:
C#
要解析结果,请使用System.XML类或更好的 - System.Xml.Linq类。一种直接的可能性是XDocument.Load(TextReader)
方法 - 您可以直接使用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 ();
}
}
返回的WebClient
流。