[英]HttpWebResponse and Int
到目前為止,我正在與REST服務集成。 打了一點障礙。 我正在通過HttpWebRequest訪問該服務。 我已成功接收響應,但是通過StreamReader運行HttpWebResponse GetResponseStream時,我得到了
<int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">427</int>.
在如何將其轉換回ac#int方面有些堅持。
有什么建議嗎?
謝謝。
您可以將int.Parse
和int.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.