我第一次要通过将XML数据集发布到URL来使用供应商的API。如果我使用http://meyerweb.com/eric/tools/dencoder/对数据集进行编码,并手动粘贴网址&数据集进入浏览器,我得到了成功的回复。
但是,当尝试使用.NET执行相同操作时,我从供应商API获得响应,指示我的数据集无效。
这是我的代码(我从其他地方复制了好的'interweb):
public void PostXML(string value1, string value2, string value3, out string responseStatus, out string responseBody)
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("https://www.vendorURL.com/API/page.html?input=");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "<DATASET>";
postData += "<FIELD1>" + value1+ "</FIELD1>";
postData += "<FIELD2>" + value2 + "</FIELD2>";
postData += "<FIELD3>" + value3 + "</FIELD3>";
postData += "</DATASET>";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Assign the status.
responseStatus = ((HttpWebResponse)response).StatusDescription;
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
responseBody = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
请记住,我是从供应商API获取回复。它只是告诉我我的数据集无效。我已经联系过该供应商的客户支持。这已经证实我的数据集本身是正确的,但在某些地方,我正在编码它不正确,因为供应商API可以识别它。
答案 0 :(得分:4)
缺少一些东西。
您应该从xml声明开始
<?xml version="1.0"?>
您还确定数据集标签是大写的吗?案例在Xml中很重要。
<?xml version="1.0"?>
<dataset><field>value</field></dataset>
此外,您可以尝试XmlWriter:
using(var writer = XmlWriter.Create(stream))
{
writer.WriteStartDocument();
writer.WriteStartElement("dataset");
writer.WriteElementString("field1", "value");
writer.WriteElementString("field2", "value");
writer.WriteElementString("field3", "value");
writer.WriteEndElement();
writer.WriteEndDocument();
}
最后联系供应商,向您发送示例代码/ API ...
答案 1 :(得分:1)
尝试在发布数据上使用System.Web.HttpUtility.UrlEncode,然后再调用“Encoding.UTF8.GetBytes(postData);”。