首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HttpWebResponse和Int

HttpWebResponse和Int
EN

Stack Overflow用户
提问于 2012-01-17 06:58:56
回答 2查看 362关注 0票数 0

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

代码语言:javascript
复制
<int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">427</int>.

在如何将其转换回c#整型上有点卡住了。

有什么建议吗?

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-17 07:02:14

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

代码语言:javascript
复制
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,所以您甚至可以这样做:

代码语言:javascript
复制
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为您处理,这是一件很棒的事情。

票数 1
EN

Stack Overflow用户

发布于 2012-01-17 07:02:22

如果您只是尝试将字符串"427“转换为int,则使用Int32.Parse方法。

代码语言:javascript
复制
var str = "427";
var number = Int32.Parse(str);  // value == 427 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8887491

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档