访问API调用并获得响应

时间:2013-05-08 20:11:12

标签: c# asp.net xml linq parsing

我正在查看namecheap api并且开始时遇到一些困难。我在设置沙盒帐户等后尝试访问api,并且示例响应采用XML格式:

<ApiResponse Status="OK" xmlns="http://api.namecheap.com/xml.response">
  <Errors />
  <Warnings />
  <RequestedCommand>namecheap.domains.check</RequestedCommand>
  <CommandResponse>
    <DomainCheckResult Domain="google.com" Available="false" />
  </CommandResponse>
  <Server>WEB1-SANDBOX1</Server>
  <GMTTimeDifference>--4:00</GMTTimeDifference>
  <ExecutionTime>0.875</ExecutionTime>
</ApiResponse>

我知道如何解析XML,但我需要一些指导,我如何开始使用API​​调用的实际请求/响应部分。

我知道需要发送哪些参数,我知道我需要api密钥和url,但是如何编写WebRequest和WebResponse部分呢?或者Linq能否为我提供实现这一目标的方法?

我试图使用:

WebRequest req = HttpWebRequest.Create(url + apikey + username + command + domain);
WebResponse response = req.GetResponse();

但是我没有办法用变量response做任何事情。

如何对此API进行非常简单的API调用并将其响应转换为XML格式,以便我可以解析它?

任何帮助都非常感谢。

2 个答案:

答案 0 :(得分:2)

您需要关联响应流并从中读取:

// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream ();

StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

Console.WriteLine ("Response stream received.");
Console.WriteLine (readStream.ReadToEnd ());

答案 1 :(得分:-2)

WebResponse是抽象的,您必须将其转换为HttpWebResponse

HttpWebResponse response = (HttpWebResponse)req.GetResponse();

然后,您就可以访问您正在寻找的各种信息。


此外,如果你只是做简单的网络请求,你可能会考虑使用WebClient,而很多更容易使用......简直就是这样:

string response = new WebClient().DownloadString("http://somewebsite.com/some/resource?params=123");