How to start a GET request through a pseudo-random REST service in C #

I need to communicate with a legacy php application. APIs are just php scripts than accepting requests to receive and return a response as XML.

I would like to write a post in C #.

What would be the best way to run a GET request (with many parameters) and then the result of the parsing?

Ideally I would like to find something as simple 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 a GET request.

0


a source to share


2 answers


The WCF REST Starter Kit has good utility classes for implementing .NET REST clients that invoke services implemented on any platform.

Shown here is a video that describes the use of client-side parts.



Sample code snippet:

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


a source


Simple is System.Net.Webclient

functionally similar python

urllib

.

An example C#

(slightly edited in the form 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 analyze the result, use the System.XML classes or better, the System.Xml.Linq classes. A direct possibility is a method XDocument.Load(TextReader)

- you can directly use the stream WebClient

returned OpenRead()

.

0


a source







All Articles