繁体   English   中英

HttpWebResponse和Int

[英]HttpWebResponse and Int

到目前为止,我正在与REST服务集成。 打了一点障碍。 我正在通过HttpWebRequest访问该服务。 我已成功接收响应,但是通过StreamReader运行HttpWebResponse GetResponseStream时,我得到了

<int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">427</int>.

在如何将其转换回ac#int方面有些坚持。

有什么建议吗?

谢谢。

您可以将int.Parseint.TryParse方法与XDocument结合使用,以将响应XML加载到以下文件中:

var request = WebRequest.Create(...);
...
using (var response = request.GetResponse())
using (var stream = response.GetStream())
{
    var doc = XDocument.Load(stream);
    if (int.TryParse(doc.Root.Value, out value))
    {

        // the parsing was successful => you could do something with
        // the integer value you have just read from the body of the response
        // assuming the server returned the XML you have shown in your question,
        // value should equal 427 here.
    }
}

XDocument的Load方法甚至更容易理解HTTP,因此您甚至可以这样做:

var doc = XDocument.Load("http://foo/bar");
if (int.TryParse(doc.Root.Value, out value))
{
    // the parsing was successful => you could do something with
    // the integer value you have just read from the body of the response
    // assuming the server returned the XML you have shown in your question,
    // value should equal 427 here.
}

这样,您甚至不需要使用任何HTTP请求/响应。 BCL将为您处理所有事情,这非常好。

如果您只是想将字符串“ 427”转换为int使用Int32.Parse方法。

var str = "427";
var number = Int32.Parse(str);  // value == 427 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM