访问和获取API调用的响应
本文关键字:响应 调用 API 获取 访问 | 更新日期: 2023-09-27 18:12:49
我正在检查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格式,以便我可以解析它?
任何帮助都是非常感谢的。
您需要获得关联的响应流并从中读取:
// 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 ());
WebResponse
是抽象的,您必须将其转换为HttpWebResponse
。
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
你将能够访问你正在寻找的各种信息。
另外,如果你只是做简单的web请求,你可以考虑使用WebClient
,它的更容易使用…就像:
string response = new WebClient().DownloadString("http://somewebsite.com/some/resource?params=123");