【问题标题】:Problem fetching XML file in Java在 Java 中获取 XML 文件的问题
【发布时间】:2011-06-26 05:29:47
【问题描述】:

我正在尝试在 Android 应用程序中使用 Google 的非官方天气 API。

我使用这个代码:

//get the text from the edit text
    userZip = zipCode.getText().toString();
    //create a link using the zip code
    //TODO sanitize input
    System.out.println(userZip);
    link = "http://www.google.com/ig/api?weather=" + userZip;
    System.out.println(link);
    //connect to the link
    URL googleWeatherService = null;
    try {
        googleWeatherService = new URL(link);
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } 
    SAXBuilder parser = new SAXBuilder();
    try {
        doc = parser.build(googleWeatherService);
    } catch (JDOMException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

但我收到错误 java.io.IOException 无法打开 http://www.google.com/ig/api?weather=08003(仅以 08003 为例)。

如果你转到 FF 中的链接,你会得到一个很好的 XML 天气文件,那我做错了什么?

【问题讨论】:

    标签: java android xml api


    【解决方案1】:

    我在使用 JDOM2 时遇到过这个问题,它实际上是变相的 NetworkOnMainThreadException。将其从主线程中移除,一切正常。

    new Thread(new Runnable() {
                @Override
                public void run() {
                    <your code>
                }
            }).start();
    

    【讨论】:

      【解决方案2】:

      您能否成功检索其他 URI?

      您可能遇到了 JVM 配置问题。在我遇到的大多数环境中,如果您的机器配置为使 Web 浏览器可以成功发出 HTTP 请求,那么 Java 也将能够成功发出它们。但是我听说当你在代理服务器后面时需要特殊的 JVM 配置,我不知道在 Android 环境中是否需要类似的配置。

      【讨论】:

        【解决方案3】:

        这对我来说非常有效:

        package weather;
        
        import org.dom4j.Document;
        import org.dom4j.io.OutputFormat;
        import org.dom4j.io.SAXReader;
        import org.dom4j.io.XMLWriter;
        
        import java.io.BufferedReader;
        import java.io.InputStreamReader;
        import java.net.URL;
        
        /**
         * GoogleWeather
         * @author Michael
         * @since 2/12/11
         */
        public class GoogleWeather
        {
        
            public static void main(String[] args)
            {
                for (String userZip : args)
                {
                    BufferedReader br = null;
                    try
                    {
                        String link = "http://www.google.com/ig/api?weather=" + userZip;
                        System.out.println(link);
                        URL googleWeatherService = new URL(link);
                        br = new BufferedReader(new InputStreamReader(googleWeatherService.openStream()));
                        SAXReader reader = new SAXReader();
                        Document document = reader.read(googleWeatherService);
                        OutputFormat format = OutputFormat.createPrettyPrint();
                        XMLWriter writer = new XMLWriter(System.out, format);
                        writer.write(document);
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                    finally
                    {
                        close(br);
                    }
                }
            }
        
            private static void close(BufferedReader br)
            {
                try
                {
                    if (br != null)
                    {
                        br.close();
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
        

        这是它带回来的结果:

        <?xml version="1.0" encoding="UTF-8"?>
        
        <xml_api_reply version="1">
          <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
            <forecast_information>
              <city data="Hebron, CT"/>
              <postal_code data="06248"/>
              <latitude_e6 data=""/>
              <longitude_e6 data=""/>
              <forecast_date data="2011-02-12"/>
              <current_date_time data="2011-02-13 03:00:47 +0000"/>
              <unit_system data="US"/>
            </forecast_information>
            <current_conditions>
              <condition data="Partly Cloudy"/>
              <temp_f data="28"/>
              <temp_c data="-2"/>
              <humidity data="Humidity: 45%"/>
              <icon data="/ig/images/weather/partly_cloudy.gif"/>
              <wind_condition data="Wind: NW at 14 mph"/>
            </current_conditions>
            <forecast_conditions>
              <day_of_week data="Sat"/>
              <low data="16"/>
              <high data="36"/>
              <icon data="/ig/images/weather/partly_cloudy.gif"/>
              <condition data="Partly Cloudy"/>
            </forecast_conditions>
            <forecast_conditions>
              <day_of_week data="Sun"/>
              <low data="30"/>
              <high data="38"/>
              <icon data="/ig/images/weather/snow.gif"/>
              <condition data="Snow Showers"/>
            </forecast_conditions>
            <forecast_conditions>
              <day_of_week data="Mon"/>
              <low data="23"/>
              <high data="46"/>
              <icon data="/ig/images/weather/cloudy.gif"/>
              <condition data="Cloudy"/>
            </forecast_conditions>
            <forecast_conditions>
              <day_of_week data="Tue"/>
              <low data="12"/>
              <high data="29"/>
              <icon data="/ig/images/weather/cloudy.gif"/>
              <condition data="Windy"/>
            </forecast_conditions>
          </weather>
        </xml_api_reply>
        

        【讨论】:

        • 这看起来很棒,但我使用的是 JDOM,而不是 dom4j,所以没有 SAXREADER……使用 JDOM 的等效过程是什么?
        • 是的,如果您愿意,您可以进行 SAX 解析。 JDOM 似乎不太适合您。这只是单个 JAR 的开关。为什么不按原样尝试,看看这是否更好?如果它真的适合你,为什么不接受呢?
        【解决方案4】:

        我认为您需要打开与 url 的连接并获取输入流以使其正常工作。我会试试这个:

         URL googleWeatherService = null;
         URLConnection conn = null;
        try {
            googleWeatherService = new URL(link);
            conn = googleWeatherService.openConnection();
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } 
        SAXBuilder parser = new SAXBuilder();
        try {
            doc = parser.build(conn.getInputStream());
        

        希望这对你有用!

        否则,如果失败,听起来您必须处理 URL 重定向,这是我曾经遇到的问题。在这种情况下,您需要执行以下操作:

         URL googleWeatherService = null;
         URLConnection conn = null;
        try {
        googleWeatherService = new URL(link);
        HttpURLConnection ucon = (HttpURLConnection) googleWeatherService.openConnection();
        ucon.setInstanceFollowRedirects(false);
        URL secondURL = new URL(ucon.getHeaderField("Location"));
        conn = secondURL.openConnection();
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } 
        SAXBuilder parser = new SAXBuilder();
        try {
            doc = parser.build(conn.getInputStream());
        

        希望这能解决它!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-02
          • 2014-05-11
          • 2013-09-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多