您的位置:首页 > 其它

国家气象局提供的天气预报接口 如何使用

2013-05-31 08:48 381 查看
import java.io.BufferedReader;  

import java.io.IOException;  

import java.io.InputStreamReader;  

import java.net.HttpURLConnection;  

import java.net.URL;  

import net.sf.json.JSONObject;

public class getWeatherJson {

    

    private URL url;  

    public String download(String urlStr) {  

        StringBuffer sb = new StringBuffer();  

        String line = null;  

        BufferedReader buffer = null;  

        try {  

            url = new URL(urlStr);  

            HttpURLConnection conn = (HttpURLConnection) url  

                    .openConnection();  

            buffer = new BufferedReader(new InputStreamReader(  

                    conn.getInputStream(),"utf-8"));  //此处不转码 会出现乱码情况

            while ((line = buffer.readLine()) != null) {  

                sb.append(line);  

            }  

        } catch (Exception e) {  

            e.printStackTrace();  

        } finally {  

            try {  

                buffer.close();  

            } catch (IOException e) {  

                e.printStackTrace();  

            }  

        }  

        return sb.toString();  

    }  

    

    public static void main(String []args){
        System.out.println(new getWeatherJson().download("http://www.weather.com.cn/data/sk/101010100.html"));

        //此处需要转成json  返回前端根据需求

        JSONObject json = JSONObject.fromString(new getWeatherJson().download("http://www.weather.com.cn/data/sk/101010100.html")); 

        JSONObject jsons = JSONObject.fromString(json.getString("weatherinfo"));

        System.out.println(jsons.getString("SD"));

        

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息