使用.Net 4.0,ASP.NET类调用简单的外部/ Web服务API

时间:2011-12-13 12:51:15

标签: asp.net .net asp.net-mvc-3 api c#-4.0

之前从未调用过API,也不确定在ASP.NET中使用哪些类 这样做。我可能会在阅读中共同理解 调用其他服务的各种例子,但希望有人可以 建议哪些更符合我的需求,这样我就可以快速入手 关于事情。使用PHP脚本调用此API的示例位于下方,因此如果有人可以打卡 使用HttpWebRequest和WebClient输出一些代码,看它在运行中会很棒 对于所述示例以及在HttpRequest中捕获来自API的回复。也可以使用Jscript从客户端/浏览器调用此类API,或者必须从服务器端调用这些API并将结果传递给客户端吗?

    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";
}
?>

1 个答案:

答案 0 :(得分:1)

只需使用WebClient.DownloadString:

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