我正在尝试创建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‘应该设置为if conditions还是try&catch。
任何指南都会很有帮助。非常感谢。
发布于 2014-09-23 17:43:34
您可能无法控制发送给您的内容,但您可以使用Accept标头请求xml。
hwrequest.Accept = "application/xml";但是,您将无法控制该结构。
发布于 2014-09-23 18:03:21
可以,您应该处理响应状态(200、201、404等)使用If/Else语句,而不是依赖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.aspx http://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()方法中。
https://stackoverflow.com/questions/25991516
复制相似问题