0

可能重复:
我需要什么权限才能从 android 应用程序访问 Internet?

我在这篇文章中遇到了 Google Weather API:http: //blog.programmableweb.com/2010/02/08/googles-secret-weather-api/

我想尝试一下,它在 Windows 上运行良好。当我在我的 Android 2.2 手机和 Android 模拟器上尝试它时,下面的代码在下面注释的地方抛出了一个 SocketException。

这是代码:

   public static String downloadPage(String pageUrl) throws IOException
   {
      URL url = new URL(pageUrl);

      HttpURLConnection conn = (HttpURLConnection)url.openConnection();

      if (conn == null)
         return null;

      conn.setRequestMethod("GET");
      conn.setDoOutput(true);

      //this throws a SocketException
      conn.connect();

      InputStream is = conn.getInputStream();
      //InputStream is = url.openStream();

      if (is == null)
         return null;

      InputStreamReader rdr = new InputStreamReader(is);

      StringBuilder sb = new StringBuilder();
      int b;

      while ((b = rdr.read()) != -1)
      {
         sb.append((char)b);
      }

      return sb.toString();
   }

   public static boolean getWeather(String city, ArrayList<String> stats)
   {
      String url = String.format("http://www.google.com/ig/api?weather=%s",
            city.replace(' ', '+'));
      try
      {
         String XML = downloadPage(url);
         //...
         return true;
      }
      catch (Exception exc)
      {
         exc.getCause();
      }

      return false;
   }

它基本上是这样称呼的:

getWeather("fairfax");

它在 PC 上运行良好。http://www.google.com/ig/api?weather=fairfax

4

0 回答 0