消费一个REST XML Web服务 [英] Consuming a REST XML web service

查看:142
本文介绍了消费一个REST XML Web服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图消耗下面的Web服务 http://ipinfodb.com/ip_location_api.php
这个Web服务返回一个XML响应,code以下获取XML响应,但不知何故从XML响应中的相位值时,这是行不通的。

什么是错我的code?

 使用系统;
使用System.Collections.Generic;
使用System.Text;
使用的System.Web;
使用System.IO;
使用System.Net;
使用的System.Xml;命名空间ConsoleApplication3
{
类节目
{
    静态无效的主要(字串[] args)
    {
        HttpWebRequest的要求= NULL;
        HttpWebResponse响应=无效;
        字符串的Xml;        //创建web请求
        请求= WebRequest.Create(\"http://api.ipinfodb.com/v2/ip_query.php?key=<yourkey>&ip=74.125.45.100&timezone=true\")为HttpWebRequest的;        //获取响应
        使用(响应= request.GetResponse()作为HttpWebResponse)
        {
            //获取响应流
            StreamReader的读者=新的StreamReader(response.GetResponseStream());            XML = reader.ReadToEnd();
        }
        //控制台XML输出
        Console.WriteLine(XML); //看看我们是否得到XML响应,(是的,我们这样做)        到Console.ReadLine();
            字符串_currentField =;
            StringReader _sr =新StringReader(XML);
            XmlTextReader的_xtr = XmlTextReader的新(_sr);
            _xtr.XmlResolver = NULL;
            _xtr.WhitespaceHandling = WhitespaceHandling.None;            //获取根节点
            _xtr.Read();            如果((_xtr.NodeType == XmlNodeType.Element)及及(_xtr.Name ==回应))
            {
                而(_xtr.Read())
                {
                    如果((_xtr.NodeType == XmlNodeType.Element)及&放大器;!(_xtr.IsEmptyElement))
                    {
                        _currentField = _xtr.Name;
                        _xtr.Read();
                        如果(_xtr.NodeType == XmlNodeType.Text)
                        {
                            开关(_currentField)
                            {
                                案状态:
                                    Console.WriteLine(_xtr.Value); //我们打印到控制台用于测试目的,通常将其分配给一个变​​量在这里!
                                    打破;
                                案国家code:
                                    Console.WriteLine(_xtr.Value);
                                    打破;
                                案国家或地区名称:
                                    Console.WriteLine(_xtr.Value);
                                    打破;
                                案地区code:
                                    Console.WriteLine(_xtr.Value);
                                    打破;
                                案RegionName:
                                    Console.WriteLine(_xtr.Value);
                                    打破;
                                案城:
                                    Console.WriteLine(_xtr.Value);
                                    打破;
                                案ZipPostal code:
                                    Console.WriteLine(_xtr.Value);
                                    打破;
                                案纬度:
                                    Console.WriteLine(_xtr.Value);
                                    打破;
                                案经度:
                                    Console.WriteLine(_xtr.Value);
                                    打破;
                                案Gmtoffset:
                                    Console.WriteLine(_xtr.Value);
                                    打破;
                                案字符dstOffset:
                                    Console.WriteLine(_xtr.Value);
                                    打破;
                                案TI​​MEZONENAME:
                                    Console.WriteLine(_xtr.Value);
                                    打破;
                                案Isdst:
                                    Console.WriteLine(_xtr.Value);
                                    打破;
                                案IP:
                                    Console.WriteLine(_xtr.Value);
                                    打破;                                默认:
                                    //未知领域
                                    (响应未知的领域。)抛出新的异常;
                            }
                        }
                    }
                }
            }
            到Console.ReadLine();
    }
}

}

编辑:这是XML响应返回

 &LT;?XML版本=1.0编码=UTF-8&GT?;
- &LT;应变及GT;
  &LT;状态&gt;&OK LT; /状态&gt;
  &LT;国家code&GT;美国和LT; /国家code&GT;
  &LT;&国家或地区名称GT;美国&LT; /国家或地区名称&GT;
  &LT;区域code&GT; 06&LT; /地区code&GT;
  &LT; RegionName&GT;&加州LT; / RegionName&GT;
  &LT;城市&GT;山景&LT; /城市&GT;
  &LT; ZipPostal code&GT; 94043&LT; / ZipPostal code&GT;
  &LT;纬度和GT;&37.4192 LT; /纬度&GT;
  &LT;经度&GT; -122.057&LT; /经度&GT;
  &LT; Gmtoffset&GT; -28800&LT; / Gmtoffset&GT;
  &所述;字符dstOffset大于0&下; /字符dstOffset&GT;
  &LT;&TIMEZONENAME GT;美洲/洛杉矶&LT; / TIMEZONENAME&GT;
  &所述; Isdst大于0&下; / Isdst&GT;
  &LT;知识产权及GT; 74.125.45.100&LT; / IP&GT;
  &LT; /响应&GT;


解决方案

我用的是同样的API,我响应XML载入到的的XDocument 并解析如

  //建立在运行时的URL设置
字符串apiKey = ConfigurationManager.AppSettings [geoApiKey];
字符串的URL =的String.Format(ConfigurationManager.AppSettings [geoApiUrl],apiKey,IP);WebRequest的请求= WebRequest.Create(URL);
尝试
{
    WebResponse的响应= request.GetResponse();
    使用(VAR SR =新就是System.IO.StreamReader(response.GetResponseStream()))
    {
        的XDocument xmlDoc中=新的XDocument();
        尝试
        {
            xmlDoc中= XDocument.Parse(sr.ReadToEnd());
            字符串状态= xmlDoc.Root.Element(状态)值。
            Console.WriteLine(响应状态:{0},地位);
            如果(状态==OK)
            {
                //如果状态确定它的正常安全承担所需元素
                // 在那儿。但是,如果你想成为安全你可以随时检查元素
                //检索值之前存在
                Console.WriteLine(xmlDoc.Root.Element(国家code)值。);
                Console.WriteLine(xmlDoc.Root.Element(国家或地区名称)值。);
                ...
            }
        }
        赶上(例外)
        {
            //处理如有必要,
        }
    }
}
赶上(引发WebException)
{
    //处理如有必要,
}

什么你也应该做的是推出一个自定义类如 GeoLocationInfo 和包装你code函数中的例如 GetGeoLocation(串IP)然后,而不是写信息给你可以填充和放控制台窗口;返回类的一个实例。

I'm trying to consume the following web service http://ipinfodb.com/ip_location_api.php this web service returns an xml response, the code below gets the XML response, but somehow when phasing the values from the XML response it does not work.

What is wrong with my code?

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Net;
using System.Xml;

namespace ConsoleApplication3
{
class Program
{
    static void Main(string[] args)
    {
        HttpWebRequest request = null;
        HttpWebResponse response = null;
        String Xml;

        // Create the web request  
        request = WebRequest.Create("http://api.ipinfodb.com/v2/ip_query.php?key=<yourkey>&ip=74.125.45.100&timezone=true") as HttpWebRequest;

        // Get response  
        using (response = request.GetResponse() as HttpWebResponse)
        {
            // Get the response stream  
            StreamReader reader = new StreamReader(response.GetResponseStream());

            Xml = reader.ReadToEnd();


        }
        // Console xml output  
        Console.WriteLine(Xml); //see if we get the xml response, (YES we do)

        Console.ReadLine();
            string _currentField = "";
            StringReader _sr = new StringReader(Xml);
            XmlTextReader _xtr = new XmlTextReader(_sr);
            _xtr.XmlResolver = null;
            _xtr.WhitespaceHandling = WhitespaceHandling.None;

            // get the root node
            _xtr.Read();

            if ((_xtr.NodeType == XmlNodeType.Element) && (_xtr.Name == "Response"))
            {
                while (_xtr.Read())
                {
                    if ((_xtr.NodeType == XmlNodeType.Element) && (!_xtr.IsEmptyElement))
                    {
                        _currentField = _xtr.Name;
                        _xtr.Read();
                        if (_xtr.NodeType == XmlNodeType.Text)
                        {
                            switch (_currentField)
                            {
                                case "Status":
                                    Console.WriteLine(_xtr.Value); //we print to console for testing purposes, normally assign it to a variable here!
                                    break;
                                case "CountryCode":
                                    Console.WriteLine(_xtr.Value);
                                    break;
                                case "CountryName":
                                    Console.WriteLine(_xtr.Value);
                                    break;
                                case "RegionCode":
                                    Console.WriteLine(_xtr.Value);
                                    break;
                                case "RegionName":
                                    Console.WriteLine(_xtr.Value);
                                    break;
                                case "City":
                                    Console.WriteLine(_xtr.Value);
                                    break;
                                case "ZipPostalCode":
                                    Console.WriteLine(_xtr.Value);
                                    break;
                                case "Latitude":
                                    Console.WriteLine(_xtr.Value);
                                    break;
                                case "Longitude":
                                    Console.WriteLine(_xtr.Value);
                                    break;
                                case "Gmtoffset":
                                    Console.WriteLine(_xtr.Value);
                                    break;
                                case "Dstoffset":
                                    Console.WriteLine(_xtr.Value);
                                    break;
                                case "TimezoneName":
                                    Console.WriteLine(_xtr.Value);
                                    break;
                                case "Isdst":
                                    Console.WriteLine(_xtr.Value);
                                    break;
                                case "Ip":
                                    Console.WriteLine(_xtr.Value);
                                    break;

                                default:
                                    // unknown field
                                    throw new Exception("Unknown field in response.");
                            }
                        }
                    }
                }
            }
            Console.ReadLine();
    }
}

}

EDIT: this is the XML response returned

  <?xml version="1.0" encoding="UTF-8" ?> 
- <Response>
  <Status>OK</Status> 
  <CountryCode>US</CountryCode> 
  <CountryName>United States</CountryName> 
  <RegionCode>06</RegionCode> 
  <RegionName>California</RegionName> 
  <City>Mountain View</City> 
  <ZipPostalCode>94043</ZipPostalCode> 
  <Latitude>37.4192</Latitude> 
  <Longitude>-122.057</Longitude> 
  <Gmtoffset>-28800</Gmtoffset> 
  <Dstoffset>0</Dstoffset> 
  <TimezoneName>America/Los_Angeles</TimezoneName> 
  <Isdst>0</Isdst> 
  <Ip>74.125.45.100</Ip> 
  </Response>

解决方案

I use the this same API, I load the response XML into an XDocument and parse e.g.

// build URL up at runtime
string apiKey = ConfigurationManager.AppSettings["geoApiKey"];
string url = String.Format(ConfigurationManager.AppSettings["geoApiUrl"], apiKey, ip);

WebRequest request = WebRequest.Create(url);
try
{
    WebResponse response = request.GetResponse();
    using (var sr = new System.IO.StreamReader(response.GetResponseStream()))
    {
        XDocument xmlDoc = new XDocument();
        try
        {
            xmlDoc = XDocument.Parse(sr.ReadToEnd());
            string status = xmlDoc.Root.Element("Status").Value;
            Console.WriteLine("Response status: {0}", status);
            if (status == "OK")
            { 
                // if the status is OK it's normally safe to assume the required elements
                // are there. However, if you want to be safe you can always check the element
                // exists before retrieving the value
                Console.WriteLine(xmlDoc.Root.Element("CountryCode").Value);
                Console.WriteLine(xmlDoc.Root.Element("CountryName").Value);
                ...
            }                
        }
        catch (Exception)
        {
            // handle if necessary
        }   
    }
}
catch (WebException)
{
    // handle if necessary    
}

What you should also do is introduce a custom class e.g. GeoLocationInfo and wrap your code in a function e.g. GetGeoLocation(string ip) then instead of writing the info to the console window you can populate & return an instance of that class.

这篇关于消费一个REST XML Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆