如何在xml中返回GetResponseStream

本文关键字:返回 GetResponseStream xml | 更新日期: 2023-09-27 18:23:57

我正在尝试创建web请求,该请求通过POST调用发送XML,并希望以XML形式返回响应。

我在回复xml方面遇到了一点困难,因为我很小,我不确定如何在下面的代码中设置它。这是我的尝试:

      // Attempt to receive the WebResponse to the WebRequest.
            using (HttpWebResponse hwresponse = (HttpWebResponse)hwrequest.GetResponse())
            {
                statusCode = (int)hwresponse.StatusCode;
                if (hwresponse != null)
                { // If we have valid WebResponse then read it.
                    using (StreamReader reader = new StreamReader(hwresponse.GetResponseStream()))
                    {
                        // XPathDocument doc = new XPathDocument(reader);
                        string responseString = reader.ReadToEnd();
                        if (statusCode == 201 )
                        {
                          //  var response = new XElement("Status",
                           //    new XElement("status_code", statusCode),
                          //     new XElement("resources_created",
                          ////         new XElement("Link"),
                          //         new XElement("href"),
                          //         new XElement("title")
                          //         ),
                          //         new XElement("warnings")
                           //        );
                            XmlDocument xmlDoc = new XmlDocument();
                            xmlDoc.Load(responseString);
                            XmlNodeList address = xmlDoc.GetElementsByTagName("Status");
                            responseData = xmlDoc.ToString();
                            reader.Close();
                        }
                    }
                }
                hwresponse.Close();
            }
        }
        catch (WebException e)
        {
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
               // XmlDocument xmlDoc = new XmlDocument();
              //  XmlNodeList address = xmlDoc.GetElementsByTagName("Status", statusCode);
               // xmlDoc.Load(xmlDoc);
            }

         //   if (e.Status == WebExceptionStatus.ProtocolError)
         //   {
              //  responseData = "Status Code : {0}" + ((HttpWebResponse)e.Response).StatusCode + "Status Description : {0}" + ((HttpWebResponse)e.Response).StatusDescription;
                // responseData "Status Description : {0}" + ((HttpWebResponse)e.Response).StatusDescription;

           // }
        }

我希望能够以以下XML格式返回响应:

<status>
<status_code>201</status_code>
<etag>12345678</etag>
<resources_created>
    <link 
        rel="http://api-info.com" 
        href="http://api-info.com/tag/Some%20Tag" 
        title="Subscriber Tag (Some Tag)" />
</resources_created>
<warnings>
    <warning>Some Warning Message</warning>
</warnings>
</status>

我还想问,我的"StatusCode"是否应该设置为条件或尝试&捕获
任何指南都会很有帮助。非常感谢。

如何在xml中返回GetResponseStream

您可能无法控制发送给您的内容,但您可以请求带有Accept标头的xml。

hwrequest.Accept = "application/xml";

但是,您将无法控制结构。

是的,您应该使用If/Else语句处理响应状态(200、201、404等),而不是依赖try/catch来处理您的逻辑。Try/Catch用于错误处理,而不是处理常规应用程序流的地方。

对于Web请求,您使用的是过时的API。除非有一个特定的限制强制您使用HttpWebRequest和HttpWebResponse,否则您应该使用更新(更简单)的API,如WebClient或HttpClient(仅限.NET 4.5)

http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspxhttp://msdn.microsoft.com/en-us/library/system.net.http.httpclient%28v=vs.118%29.aspx

对于响应处理,我建议使用Linq-to-XML,而不是旧的XmlDocument API。

如果您的响应XML在XML文档的根位置有"status"元素,那么您可以执行以下操作:

var xmlDoc = XDocument.Load(reader);
var statusXml = xmlDoc.ToString();

如果"status"元素是另一个根XML元素的子元素,那么您可以执行以下操作:

var xmlDoc = XDocument.Load(reader);
var statusElement = xmlDoc.Root.Element("status");
var statusXml = statusElement.ToString();

如果你仍然想使用旧的HTTP API,你可以摆脱

string responseString = reader.ReadToEnd();

并在XDocument.Load方法中直接传递StreamReader,如我的示例所示。

如果您将解决方案升级为使用例如WebClient,则可以使用DownloadString()方法,然后将字符串结果加载到XDocument.load()方法中。