简体   繁体   English

HttpWebResponse和Int

[英]HttpWebResponse and Int

I am integrating with a REST service and so far so good. 到目前为止,我正在与REST服务集成。 Hit a little bit of a hurdle. 打了一点障碍。 I am hitting the service via a HttpWebRequest. 我正在通过HttpWebRequest访问该服务。 I am receiving responses successfully, but in running the HttpWebResponse GetResponseStream through a StreamReader, i am getting back an 我已成功接收响应,但是通过StreamReader运行HttpWebResponse GetResponseStream时,我得到了

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

A little stuck on how to convert this back to ac# int. 在如何将其转换回ac#int方面有些坚持。

Any advice? 有什么建议吗?

Thanks. 谢谢。

You may take a look at the int.Parse and int.TryParse methods in conjunction with a XDocument which you could use to load the response XML into: 您可以将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.
    }
}

or even easier, the Load method of XDocument understands HTTP, so you could even do this: 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.
}

this way you don't even need to use any HTTP requests/responses. 这样,您甚至不需要使用任何HTTP请求/响应。 Everything will be handled for you by the BCL which is kinda great. BCL将为您处理所有事情,这非常好。

If you're just trying to convert the string "427" to an int then use the Int32.Parse method. 如果您只是想将字符串“ 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