调用百度天气接口

来源:互联网 发布:淘宝的实名认证在哪里 编辑:程序博客网 时间:2024/06/02 02:59
package com.gateguard.common;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
public class Weather {
 
   public static void main(String[] args) { 
      //1.去读文件,如何存在
    downloadLocal("沈阳","D://text");
     String filePath = "D://text//text.txt";
//        "res/";
         readTxtFile(filePath);
    //1)读取文件中的内容,拿到日期做比较,相同,直接取文件中的内容
    //2)日期不相同,调用下边的方法,调用完方法取文件
    //2.文件不存在,调用下面创建文件的方法,取文件

   } 


//读取本地存放天气信息的文件。

   public static void readTxtFile(String filePath){
       try {
               String encoding="GBK";
               File file=new File(filePath);
               if(file.isFile() && file.exists()){ //判断文件是否存在
                   InputStreamReader read = new InputStreamReader(
                   new FileInputStream(file),"gbk");//考虑到编码格式
                   BufferedReader bufferedReader = new BufferedReader(read);
                   String lineTxt = null;
                   while((lineTxt = bufferedReader.readLine()) != null){
                       //System.out.println(lineTxt);
                   }
                   read.close();
       }else{
           System.out.println("找不到指定的文件");
       }
       } catch (Exception e) {
           System.out.println("读取文件内容出错");
           e.printStackTrace();
       }
    
   }
//调用百度天气接口,存信息到本地。(百度天气接口的调用有天气限制)         
public static void downloadLocal(String cityName,String downloadAddress){
        String str="";
           String weatherInform = getWeatherInform(cityName);           
           String bean2Json = JsonUtils.bean2Json(weatherInform);
           Map json2Map = JsonUtils.json2Map(bean2Json);
           String date= (String)json2Map.get("date");
           List resList = (List) json2Map.get("results");
           if(resList.size()>0){
            Map resMap = (Map) resList.get(0);
            List dataList = (List) resMap.get("weather_data");
            if(dataList.size()>0){
            Map dataMap = (Map) dataList.get(0);
           String wind = (String)dataMap.get("wind");
           String  weather = (String)dataMap.get("weather");
           String  temperature = (String)dataMap.get("temperature");
           String  dayPictureUrl = (String)dataMap.get("dayPictureUrl");
           str="wind:"+wind+"[weather:"+weather+"[temperature:"+temperature+"[dayPictureUrl:"+dayPictureUrl+"[date:"+date; 
              System.out.println(str);
            }            
           } 
           FileWriter fw = null;
           File f = new File(downloadAddress+"//text.txt");
            try {
             if(!f.exists()){
              f.createNewFile();
             }
             fw = new FileWriter(f);
             BufferedWriter out = new BufferedWriter(fw);
             out.write(str);
             out.close();
            } catch (IOException e) {
             e.printStackTrace();
            }        
      
}   
    调用百度天气接口
public static String getWeatherInform(String cityName) {
// 百度天气API
String baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=YGtqUyHOKe5xtaDzi2pmMZVEMdDNlG8F";
StringBuffer strBuf;
try {
// 通过浏览器直接访问http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=TCfuGwzNwmtVvgWfGHW69oaD
// W69oaDTCfuGwzNwmtVvgWfGH 是我自己申请的一个AK(许可码),如果访问不了,可以自己去申请一个新的ak
//新申请的ak码
//YGtqUyHOKe5xtaDzi2pmMZVEMdDNlG8F
// 百度ak申请地址:http://lbsyun.baidu.com/apiconsole/key
// 要访问的地址URL,通过URLEncoder.encode()函数对于中文进行转码
baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location=" + URLEncoder.encode(cityName, "utf-8") + "&output=json&ak=http://api.map.baidu.com/telematics/v3/weather?location=%E5%8C%97%E4%BA%AC&output=json&ak=YGtqUyHOKe5xtaDzi2pmMZVEMdDNlG8F";
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
strBuf = new StringBuffer();
try {
URL url = new URL(baiduUrl);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));// 转码。
String line = null;
while ((line = reader.readLine()) != null)
strBuf.append(line + " ");
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return strBuf.toString();
}
}
0 0
原创粉丝点击