XML响应错误:在文档的顶级无效

时间:2013-11-22 19:38:15

标签: c# xml namevaluecollection

我收到错误,并按照我收到的关于如何编码请求的API手册。以下是我的要求..

string url = "[My url to send request to]";

string xmlrequest = "<serv_request><head><securityContext><account>[account]</account><key>[my account key]</key></securityContext></head><body><username>[my user name]</username></body></serv_request>";

NameValueCollection nvc = new NameValueCollection();
nvc.Add("xml", Server.UrlEncode(xmlrequest));


WebClient client = new WebClient();

byte[] byteresponse = client.UploadValues(url, nvc);

string xmlresponse = client.Encoding.GetString(byteresponse);

我收到了错误回复。在文档的顶层无效。

编辑..添加提供给我的API手册中的说明..

string url = " http://[domain_name]/_gateway/api/[filename].asp"; 

// formulate the XML request here 

string xmlrequest = "<serv_request>...</serv_request>";  

NameValueCollection nvc = new NameValueCollection(); 
nvc.Add("xml", Server.UrlEncode(xmlrequest)); 

WebClient client = new WebClient(); 
byte[] byteresponse = client.UploadValues(url, nvc); 

string xmlresponse = client.Encoding.GetString(byteresponse); 

2 个答案:

答案 0 :(得分:1)

我设法解决了这个问题。我没有使用所有xml传递一个字符串并使用Server.UrlEncode,而是使用了XmlWriter类和StringBuilder。你所有的回复都很有帮助而且很有帮助,我会投票给他们,但我还不能做那个功能。也许这将有助于未来的其他人。感谢

        XmlWriter writer;
        StringBuilder sb = new StringBuilder();
        writer = XmlWriter.Create(sb);
        writer.WriteStartElement("serv_request");
        writer.WriteStartElement("head");
        writer.WriteStartElement("securityContext");
        writer.WriteStartElement("account");
        writer.WriteString("MyAccountName");
        writer.WriteEndElement();
        writer.WriteStartElement("key");
        writer.WriteString("MyKey");
        writer.WriteEndElement(); //closes Key Element
        writer.WriteEndElement(); // closes securityContent
        writer.WriteEndElement(); //closes head
        writer.WriteStartElement("body");
        writer.WriteStartElement("username");
        writer.WriteString("MyUserName");
        writer.WriteEndElement(); // closes username
        writer.WriteEndElement(); //closes body
        writer.WriteEndElement(); //closes serv_request
        writer.Close();

        NameValueCollection nvc = new NameValueCollection();           
        nvc.Add("xml", sb.ToString());          

        WebClient client = new WebClient();
        byte[] byteresponse = client.UploadValues(url, nvc);

        string xmlresponse = client.Encoding.GetString(byteresponse);

答案 1 :(得分:0)

听起来服务器没有使用正确的xml响应,它可能返回一个空字符串或任何不是格式良好的XML的文本。

尝试并捕获您发送的xml,并使用soapUI等工具发送请求并查看它给您的响应。

也许可以试试这个而不是你的最后一行代码:

string xmlresponse = System.Text.Encoding.UTF8.GetString(byteresponse);