tags:

views:

206

answers:

2

I need to communicate with legacy php application. The API is just a php scripts than accepts get requests and return a response as XML.

I'd like to write the communication in C#.

What would be the best approach to fire a GET request (with many parameters) and then parse result?

Ideally I would like to find something that easy as the python code below:

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

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

UPDATE: I'm thinking about using XElement.Load but I don't see a way to easily build the GET query.

A: 

A simple System.Net.Webclient is functionally similar to python's urllib.

The C# example (slightly edited form the ref above) shows how to "fire a GET request":

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

To parse the result, use System.XML classes, or better - System.Xml.Linq classes. A straightforward possibility is the XDocument.Load(TextReader) method - you can use the WebClient stream returned by OpenRead() directly.

gimel
Piotr Czapla
Sorry, example changed to use HttpUtility.UrlEncode(String, Encoding)
gimel
There's a url builder, I think, included as part of the WCF REST Starter Kit.
Cheeso
+1  A: 

There are some good utility classes in the WCF REST Starter Kit, for implementing .NET REST clients that invoke services implemented in any platform.

Here's a video that describes how to use the client-side pieces.

Sample code fragment:

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();
Cheeso