1. 程式人生 > >java天氣預報呼叫百度介面實現

java天氣預報呼叫百度介面實現

package com.cn.weather;
import java.io.BufferedReader;
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;  
public class BaiDu {

    //根據城市獲取天氣資訊的java程式碼  
    //cityName 是你要取得天氣資訊的城市的中文名字,如“北京”,“深圳”  
static String  getWeatherInform(String cityName){  


//百度天氣API  
String baiduUrl = null;
try {
baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location="+URLEncoder.encode(cityName, "utf-8")+"&output=json&ak=W69oaDTCfuGwzNwmtVvgWfGH";
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}  
StringBuffer strBuf;  




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();  
}  




public static void main(String[] args){
BaiDu baidu = new BaiDu();
System.out.println(baidu.getWeatherInform("海淀"));
}
}