其他分享
首页 > 其他分享> > Android 下载谷歌天气预报

Android 下载谷歌天气预报

作者:互联网

String GetWeather()
{
   String url = null;
   String encode = null;
   main.cursorCity.moveToPosition(nCurCityListIndex);
   if(Locale.getDefault().equals(Locale.SIMPLIFIED_CHINESE))
   {
    url = http://www.google.com/ig/api?hl=zh-cn&weather=,,,31410000,121480000));
    encode = "GB2312";
   }
   else if(Locale.getDefault().equals(Locale.TRADITIONAL_CHINESE))
   {
    url = http://www.google.com/ig/api?hl=zh-tw&weather=,,,31410000,121480000));
    encode = "BIG5";
   }
   else if(Locale.getDefault().equals(Locale.FRANCE))
   {
    url = http://www.google.com/ig/api?hl=fr-fr&weather=,,,31410000,121480000));
   }
   else
   {
    url = http://www.google.com/ig/api?hl=en-uk&weather=,,,31410000,121480000));
   }
   Downloader downLoader = new Downloader();
   String sWeatherData = downLoader.download(url,encode);//sWeatherData为下载到的天气预报
}
 
public class Downloader
{
 /**
  * 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文本当中的内容
  * 1.创建一个URL对象
  * 2.通过URL对象,创建一个HttpURLConnection对象
  * 3.得到InputStream
  * 4.从InputStream当中读取数据
  * @param urlStr
  * @return
  */
 public String download(String szUrl,String szEncode)
 {
  StringBuffer szBuffer = new StringBuffer();
  BufferedReader bufferReader = null;
  try
  {
   URL url = new URL(szUrl);
   HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
   InputStream inStream = urlConn.getInputStream();
   
   InputStreamReader inReader = null;
   if(szEncode==null)
    inReader = new InputStreamReader(inStream);
   else
    inReader = new InputStreamReader(inStream,szEncode);
   
   bufferReader = new BufferedReader(inReader);
   String line = null;
   while((line = bufferReader.readLine())!=null)
   {
    szBuffer.append(line);
   }
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
  finally
  {
   try
   {
    if(bufferReader!=null)
     bufferReader.close();
   }
   catch(Exception e)
   {
    e.printStackTrace();
   }
  }
  return szBuffer.toString();
 }
}

 

标签:String,url,谷歌,URL,Locale,new,Android,null,天气预报
来源: https://blog.51cto.com/u_15298588/3034405