我有 API,我需要以 XML 格式发送请求以获取响应(也以 XML 格式)。我认为这被称为 SOAP API,但我不确定,所以我在这里插入我发送的内容。
请求应如下所示:
<request>
<login>name</login>
<password>password</password>
<hotId>1</hotId>
</request>
我应该将它发送到这个 url 以获得响应:https://api.xxx.com/v1/hotel/get
这是如何将其与 php 和 curl 一起使用:
<?php
$login = '*****';
$password = '*****';
$request =
'<?xml version="1.0"?>' . "\n" .
'<request>' .
'<login>' . htmlspecialchars($login) . '</login>' .
'<password>' . htmlspecialchars($password) . '</password>' .
'<hotId>1</hotId>' .
'</request>';
$ch = curl_init('https://api.xxx.com/x1/hotel/get');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
echo "<pre>\n";
echo htmlspecialchars($response);
echo "</pre>";
那么在 C# 中如何做到这一点的最佳方法是什么?
我尝试了类似的方法,但它不起作用,我认为必须有更好的方法。
System.Net.WebRequest req = System.Net.WebRequest.Create(@"https://api.xxx.com/v1/hotel/get");
req.ContentType = "text/xml";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("<?xml version=\"1.0\"?><request><login>login</login><password>pass</password><hotId>1</hotId></request>");
req.ContentLength = bytes.Length;
Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
System.Net.WebResponse resp = req.GetResponse();
if (resp == null) return;
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
string responsecontent = sr.ReadToEnd().Trim();
编辑:获取使用 wsdl.exe 生成的方法。我在这里缺少新对象 [] 的登录名和密码参数,但不知道如何添加它们。
[System.Web.Services.Protocols.SoapRpcMethodAttribute("http://api.xxx.com/v1/hotel/get", RequestNamespace="http://api.xxx.com/v1/hotel/", ResponseNamespace="http://api.xxx.com/v1/hotel/", Use=System.Web.Services.Description.SoapBindingUse.Literal)]
[return: System.Xml.Serialization.XmlElementAttribute("hotel")]
public hotelType get(int hotId) {
object[] results = this.Invoke("get", new object[] {
hotId});
return ((hotelType)(results[0]));
}
构造函数:
public HotelService() {
this.Url = "http://api.xxx.com/v1/hotel/";
}