【问题标题】:HttpWebResponse and IntHttpWebResponse 和 Int
【发布时间】:2012-01-16 22:58:56
【问题描述】:

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

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

关于如何将其转换回 c# int 有点卡住。

有什么建议吗?

谢谢。

【问题讨论】:

  • 是否需要将字符串“427”转换为整数?还是您请求的页面的状态码?
  • 啊抱歉刚刚意识到回复已从我的帖子中删除。见下文。取回一个 XSD int。
  • schemas.microsoft.com/2003/10/Serialization/">427</…>

标签: c# httpwebresponse


【解决方案1】:

您可以查看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 为您处理,这非常棒。

【讨论】:

  • @Franky,看到什么?我什么都没看到。你更新了你的帖子还是什么?您对问题发表的评论毫无用处。完全不可读。如果您想显示一些 XML,请更新您的原始问题并正确格式化。
  • 达伦 - 不太确定 - 没有意识到我可以编辑原件......相反,我将其添加到评论中......感谢您更新它。
  • @Franky,好的,既然您的问题格式正确,我已经更新了我的答案以考虑您拥有的 XML。
  • @Darren - 不幸的是,如果我将流传递给 Load() 方法,我会收到“root elemeent is missing error”,如果我将 stream.ReadToEnd 传递给 Load(),我会收到'路径中的非法字符。错误。
  • @Franky,那么您还没有向我们展示服务器发送的确切响应。您不应将 stream.ReadToEnd() 传递给 Load 方法。您应该只传递响应流。但是当然,如​​果服务器没有发送有效的 XML(根据您的问题,我们都认为它正在发送),那么您将必须向我们展示服务器正在发送的确切内容。您不能只向 XDocument 提供任何内容。它必须是 XML。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2012-12-01
    • 1970-01-01
    • 2012-02-26
    • 2011-10-07
    • 1970-01-01
    • 2023-03-14
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多