Search code examples
c#phpasp.net.netasp.net-mvc-3

Calling a simple external/web service API using .Net 4.0, ASP.NET classes


Never called an API before and not sure which classes to use in ASP.NET to do so. I could probably scrape an understanding together from reading various examples of calls to other services, but was hoping someone could suggest which ones would be more specific to my needs so I can get a quick start on things. An example of calling this API with PHP script is located below, so if someone could punch out some code using the HttpWebRequest and WebClient, seeing it in action would be great for said example as well as capturing the reply from the API in the HttpRequest. Also is it possible to call such API's from the client/browser using Jscript or must these calls be made from serverside and result passed to client after?

    OUTPUT: The API will output the fields below:

error   If any error occurs while processing your request, this field will contain an error message. Otherwise, 'OK' will be returned.
eta It's a string containing the Estimated Time of Arrival
price   The price charged to deliver the goods. GST is already included.
Note that in the output, fields will be line-separated (character '\n') and each line will contain a field name and respective value separated by '='. See example below.

error=OK
eta=Overnight
price=14.52
The following piece of code is a simple example of how to access our Calculator API using PHP.

<?
$calculator_url = "http://www.e-go.com.au/calculatorAPI";

/* from/to postcodes */
$pickup   = 2000; //From Sydney
$delivery = 4000; //From Brisbane

/* Dimensions */
$width  = 40;
$height = 35;
$depth  = 65;
$weight = 2;

$ego_params  = "?pickup=$pickup&delivery=$delivery";
$ego_params .= "&width=$width";
$ego_params .= "&height=$height&depth=$depth&weight=$weight";
$ego_quote  = file($calculator_url . $ego_params);

foreach ($ego_quote as $num=>$quote) {
    $quote = trim($quote);
    $quote_field = explode("=", $quote);
    print "Field=" . $quote_field[0] . "\tValue=" . $quote_field[1] . "\n";
}
?>

Solution

  • Just use WebClient.DownloadString:

    http://msdn.microsoft.com/en-us/library/fhd1f0sw(v=vs.80).aspx