同步于中国天气网的第三方天气API(Json,XML)/可套用Demo in Java

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/XGL1569348/article/details/72797511

http://wthrcdn.etouch.cn/WeatherApi?city=
http://wthrcdn.etouch.cn/weather_mini?city=

两个链接后加上UrlEncoded城市名字就能获得信息。
前者为XML,后者为Json。包括当天的具体天气信息,生活指数,以及未来五天的天气信息。
XML的数据在生活指数上更为丰富。

http://wthrcdn.etouch.cn/weather_mini?citykey=
http://wthrcdn.etouch.cn/WeatherApi?citykey=
这两个需要通过通过城市id来访问,获得的内容同上,ID列表见
http://cj.weather.com.cn/support/Detail.aspx?id=51837fba1b35fe0f8411b6df
城市ID数据txt:
https://drive.google.com/file/d/0B9zkTpK3eXCGc01XM2xPeHFSdEU/view?usp=sharing

需要注意的是,Json数据被GZIP压缩。
Java应用下测试需要解压。
安卓环境下测试不需要解压,不知道为什么。
所以建议抽取前两个字节判断是否为0x1f8b(GZIP的header)再操作比较稳妥。

彩云天气上有免费的逐小时预报的API,不过需要注册审核,不然只能用token测试账号,如果审核完毕,我也写个demo。

使用gson解析json的Demo如下。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
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.HashMap;
import java.util.Scanner;
import java.util.zip.GZIPInputStream;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * @HowToUse You should use constructor by city's name, and use setJsonProject(method) to prepare for data.
 * @author Dell
 */
public class Weather {
    private static String CharSet = "UTF-8";
    private String city;
    private JsonObject jsonOrinal;
    private JsonObject jsonData;
    private JsonArray jsonForecastArray;

    //testing
    public static void main(String[] args) {
        System.out.print("Query:");
        Scanner input = new Scanner(System.in);
        String inputCity = input.next();
        input.close();
        Weather weather = new Weather(inputCity);
        if(weather.setJsonProject()==1){//Query Successfully

            System.out.println("City:"+ weather.getCity());
            System.out.println("℃:"+ weather.getTemperatureNow());
            System.out.println("AQI:"+ weather.getAQI());
            System.out.println("Tomorrow's highest ℃:"+ weather.getSomeDaydata(0).get("high"));
        }else{
            System.out.println("Error!");
        }
    }


    public Weather(String city) {
        this.city = city;
    }

    /**
     * <p> change the word to UrlEncoded</p>
     * @param word the word waiting to be urlencoded
     * @return UrlEncoded string urlencoded
     */
    static private String ToUrlEncoded(String word) {
        String urlStr = null;
        try {
            urlStr = URLEncoder.encode(word,CharSet);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return urlStr;
    }

    /**
     * <p> prepare JsonProject for outside using</p>
     * @return 1:success -1:invalid city name 0:Error
     */
    public int setJsonProject() {
        try {

            URL url = new URL("http://wthrcdn.etouch.cn/weather_mini?city="+ToUrlEncoded(this.city));
            URLConnection urlConnection = url.openConnection();

            //GZIP or not
            InputStream is;
            BufferedInputStream bis = new BufferedInputStream(urlConnection.getInputStream());  
            bis.mark(2);
            byte[] header = new byte[2];
            int result = bis.read(header);
            bis.reset();
            //Judge header
            int headerData = (int) ((header[0] << 8) | header[1] & 0xFF);
            if (result != -1 && headerData == 0x1f8b) {  
                is = new GZIPInputStream(bis);  
            } else {  
                is = bis;  
            }

            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader bReader = new BufferedReader(isr);

            StringBuilder sbWeather = new StringBuilder();
            String line;

            while((line = bReader.readLine()) != null){
                sbWeather.append(line);
            }
            bReader.close();

            JsonParser parser = new JsonParser();
            this.jsonOrinal = (JsonObject) parser.parse(sbWeather.toString());
            //check json data
            if(this.jsonOrinal.get("status").getAsInt()==1000){
                jsonData = this.jsonOrinal.get("data").getAsJsonObject();
                jsonForecastArray = jsonData.get("forecast").getAsJsonArray();
                return 1;
            }else{
                return -1;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * <p> get AQI num</p>
     * @return String AQI Data
     */
    public String getAQI() {
        try{
            return this.jsonData.get("aqi").getAsString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Failed";
    }

    /**
     * <p> get Temperature Now</p>
     * @return String Temperature right now as ℃
     */
    public String getTemperatureNow() {
        try{
            return this.jsonData.get("wendu").getAsString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Failed";
    }

    /**
     * <p> get City's name</p>
     * @return String City name
     */
    public String getCity() {
        try{
            return this.jsonData.get("city").getAsString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Failed";
    }

    /**
     * <p> get weather information of a specific day<br>
     * return a hashmap which contents weather information of 5 days in the future including highest and lowest
     * temperature, date, wind grading, weather type
     * </p>
     * @return HashMap the hashmap in introduction
     */
    public HashMap<String, String> getSomeDaydata(int day) {
        if(day >= 0 && day <=4){
            try {
                HashMap<String, String> day2Map = new HashMap<String, String>();
                JsonObject day2Object = this.jsonForecastArray.get(day).getAsJsonObject();
                day2Map.put("date", day2Object.get("date").getAsString());
                day2Map.put("high", day2Object.get("high").getAsString());
                day2Map.put("low", day2Object.get("low").getAsString());
                day2Map.put("windGrade", day2Object.get("fengli").getAsString());
                day2Map.put("type", day2Object.get("type").getAsString());
                return day2Map;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * <p> get tips about cold</p>
     * @return String Cold infomation
     */
    public String getColdInfo(){
        try{
            return jsonData.get("ganmao").getAsString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

猜你喜欢

转载自blog.csdn.net/XGL1569348/article/details/72797511
今日推荐