简体   繁体   中英

HttpWebResponse and Int

I am integrating with a REST service and so far so good. Hit a little bit of a hurdle. I am hitting the service via a HttpWebRequest. I am receiving responses successfully, but in running the HttpWebResponse GetResponseStream through a StreamReader, i am getting back an

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

A little stuck on how to convert this back to 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:

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:

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. Everything will be handled for you by the BCL which is kinda great.

If you're just trying to convert the string "427" to an int then use the Int32.Parse method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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