欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

360天气信息获取

程序员文章站 2022-03-22 20:24:17
...

懒得每次都要去找接口,还是自己整理一下好了。
步骤一:百度定位服务 key and service 拿到城市名称
360天气信息获取
360天气信息获取
360天气信息获取
步骤二:本地数据库保存城市名称和匹配的城市id号
360天气信息获取
360天气信息获取
步骤三:volley网络请求根据城市名称或者城市ID号获取天气信息

public static void loadWeatherInfo(String city, final CalendarWeatherCallBack callback) {
        if (weather == null) {
            weather = new Weather();
        }

        if (city.contains("市")) {
            city = city.replace("市", "");
        }

        try {
            city = URLEncoder.encode(city, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // String url = "http://wthrcdn.etouch.cn/weather_mini?city=" + city;
        String url = String.format(baseUrl, city);
        StringRequest request = new StringRequest(url, new Listener<String>() {
            @Override
            public void onResponse(String arg) {
                String result = "";
                try {
                    result = new String(arg.getBytes("iso-8859-1"), "utf-8");
                } catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                }
                try {
                    JSONObject object = new JSONObject(result);
                    if ("OK".equals(object.getString("desc"))) {
                        JSONArray forecast = object.getJSONObject("data").getJSONArray("forecast");
                        JSONObject today = (JSONObject) forecast.get(0);
                        String low = today.getString("low");
                        String high = today.getString("high");
                        String type = today.getString("type");

                        if (low.contains("低温")) {
                            low = low.replace("低温", "");
                        }
                        if (high.contains("高温")) {
                            high = high.replace("高温", "");
                        }

                        weather.setHigh(high);
                        weather.setLow(low);
                        weather.setType(type);
                        weather.setResId(getWeatherIconResId(type));

                        callback.onCalendarWeatherSuccess(weather);
                    } else {
                        callback.onCalendarWeatherError();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    callback.onCalendarWeatherError();
                }
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                callback.onCalendarWeatherError();
            }
        });
        WeatherApplication.getVolleyRequestQueue().add(request);
    }

源码点击下载