代码之家  ›  专栏  ›  技术社区  ›  Piotr Czapla

如何通过C中的伪REST服务发出get请求#

  •  0
  • Piotr Czapla  · 技术社区  · 16 年前

    我需要与传统的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查询的方法。

    2 回复  |  直到 16 年前
        1
  •  1
  •   Cheeso    16 年前

    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(); 
    
        2
  •  0
  •   gimel    16 年前

    简单的 System.Net.Webclient 功能上类似于 python urllib .

    这个 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) 方法-您可以使用 WebClient 流返回者 OpenRead() 直接。