有谁知道为什么HttpURLConnection.connect()抛出SocketException?

时间:2011-08-26 01:07:30

标签: java android networking httpurlconnection socketexception

  

可能重复:
  What permission do I need to access Internet from an android application?

我在这篇文章中遇到了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");

它可以在电脑上正常工作。 http://www.google.com/ig/api?weather=fairfax

0 个答案:

没有答案