【问题标题】:Accessing and getting response from API call访问和获取 API 调用的响应
【发布时间】:2013-05-08 20:11:12
【问题描述】:

我正在查看 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 key 和 url,但是如何编写其中的 WebRequest 和 WebResponse 部分?或者,Linq 也可以为我提供实现这一目标的方法吗?

我正在尝试使用:

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

但我看不到用变量 response 做任何事情的方法。

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

非常感谢任何帮助。

【问题讨论】:

    标签: c# asp.net xml linq parsing


    【解决方案1】:

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

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

    【讨论】:

    • 为什么这被否决了?对我来说,这似乎是正确的答案。 readStream.ReadToEnd() 将在响应中返回一串内容。
    • 不知道。谢谢你的帮助:-)
    【解决方案2】:

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

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

    然后,您将能够访问您正在寻找的各种信息。


    此外,如果您只是在处理简单的网络请求,您可以考虑使用WebClient,它要容易得多使用...就像简单的一样:

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

    【讨论】:

    • 谢谢SpikeX,但所做的只是在页面上显示System.Net.HttpWebResponse。完全没有反应。
    • 您没有显示显示任何内容的代码部分,所以我没有提供帮助。如果您需要更多帮助,则需要显示更多代码。我无法读懂你的想法。
    • @SpikeX 为什么从我的帖子中删除评论?您最初从 MSDN 发布的链接显示的代码与我发布的代码完全相同 - 因为我就是从那里得到它的 - 那么我的答案又出了什么问题?
    • 没什么问题,这就是我删除评论的原因。我认为这很明显。
    • @Joey - 你不能只做 response.ToString() - 你需要获取响应流并阅读它,就像在 Icarus 的回答中一样。
    猜你喜欢
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 2020-02-02
    • 2018-10-25
    相关资源
    最近更新 更多