360天气信息获取

懒得每次都要去找接口,还是自己整理一下好了。
步骤一:百度定位服务 key and service 拿到城市名称
这里写图片描述
这里写图片描述
这里写图片描述
步骤二:本地数据库保存城市名称和匹配的城市id号
这里写图片描述
这里写图片描述
步骤三: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);
    }

源码点击下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值