[Volley+Gson]获取PM2.5小应用


最近广州的空气质量真心不行,最高PM2.5都到了200+,咳咳,本来就宅的人只能更宅了。。。

今天我们会做一个简单的apk,来获取空气质量的相关数据。数据来源:百度API , 空气质量相关API,请点击

先贴一下百度的Java示例

<span style="font-family:Microsoft YaHei;">String httpUrl = "http://apis.baidu.com/apistore/aqiservice/aqi";
String httpArg = "city=%E5%8C%97%E4%BA%AC";
String jsonResult = request(httpUrl, httpArg);
System.out.println(jsonResult);

/**
 * @param urlAll
 *            :请求接口
 * @param httpArg
 *            :参数
 * @return 返回结果
 */
public static String request(String httpUrl, String httpArg) {
    BufferedReader reader = null;
    String result = null;
    StringBuffer sbf = new StringBuffer();
    httpUrl = httpUrl + "?" + httpArg;

    try {
        URL url = new URL(httpUrl);
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        connection.setRequestMethod("GET");
        // 填入apikey到HTTP header
        connection.setRequestProperty("apikey",  "您自己的apikey");
        connection.connect();
        InputStream is = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
            sbf.append(strRead);
            sbf.append("\r\n");
        }
        reader.close();
        result = sbf.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}</span>

按理说上面代码直接贴到我们主函数上就可以用了,但是实际上会有问题,因为主线程是不能做网络相关的耗时操作的,不然就会报错,所以我这里用volley来获取网络数据

通过下面三点来完成我们的网络请求

1. 拼接URL

<span style="font-family:Microsoft YaHei;">String httpUrl = "http://apis.baidu.com/apistore/aqiservice/aqi";
String httpArg = "city=%E5%8C%97%E4%BA%AC";
httpUrl = httpUrl + "?" + httpArg;</span>

2. 请求数据的方法

<span style="font-family:Microsoft YaHei;">connection.setRequestMethod("GET");</span>

3. header,也就是填入apikey

<span style="font-family:Microsoft YaHei;"> connection.setRequestProperty("apikey",  "您自己的apikey");</span>


OK, 我们也是按照上面的步骤,一点一点来写我们的Volley请求

1. 拼接URL,这个和百度的demo是一样的

<span style="font-family:Microsoft YaHei;">    String httpUrl = "http://apis.baidu.com/apistore/aqiservice/aqi";
    String httpArg = "city=";
    String url = httpUrl + "?" + httpArg + mCityName;</span>

2. 请求数据的方法

<span style="font-family:Microsoft YaHei;">JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,url,null, new Response.Listener<JSONObject>() {
         </span>
这里我们使用GET方法,请求返回JsonObject类型的数据

3. header,也就是填入apikey

<span style="font-family:Microsoft YaHei;">@Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("apikey","您自己的apikey");
                return map;
            }</span>
使用getheader方法来对apikey赋值

完成上门三步,只需要再重写onResponse 以及 onResponse.ErrorListener,最后加入到请求队列中(完整代码请参考篇末),就可以获取到JsonObject数据,转换成String类型打印出来是这个样子的:

<span style="font-family:Microsoft YaHei;">{"errNum":0,"retMsg":"success","retData":{"city":"广州","time":"2016-01-04T17:00:00Z","aqi":86,"level":"良","core":"颗粒物(PM2.5)"}</span>

好吧,如果直接这样打印出来,很丑,所以我们要润色下,解析然后提取我们需要的信息呈现给用户,这里,我们使用Gson进行解析~

<span style="font-family:Microsoft YaHei;">public class AqiInfo {

    public Aqi retData;
    static public class Aqi {
        public String city;
        public String time;
        public int aqi;
        public String level;
        public String core;
    }</span>

定义一个AqiInfo,切记参数的名字一定要和我们获取的Json数据对应,少了可以(比如errorNum,retMsg可以不加),但是错了一定不行!!!我就是因为写错了个名字,浪费了半个小时,一致解析不了,囧

然后对使用Gson对Json进行解析,并赋值给aqiInfo变量

<span style="font-family:Microsoft YaHei;">aqiInfo = gson.fromJson(response.toString(), AqiInfo.class);</span>

下面是获取PM2.5完整的实现代码

<span style="font-family:Microsoft YaHei;">void GetPM25Value(String mCityName) {
        String url = httpUrl + "?" + httpArg + mCityName; //make the url
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,url,null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.e("PM25",response.toString());
                aqiInfo = gson.fromJson(response.toString(), AqiInfo.class);
                String mTime = aqiInfo.retData.time.substring(11,19);
                mTv.setText(aqiInfo.retData.toString()+"time : "+ mTime + ",Today ");
            }
        } ,new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("PM25",error.getMessage());
                mTv.setText("Plz Check Your NetWork Connect");
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("apikey","您的用户apikey");
                return map;
            }
        };
        mQueue.add(request);
    }</span>

实现的效果如下图,非常简陋的UI

[Volley+Gson]获取PM2.5小应用_第1张图片


代码下载请猛戳这里 

相关下载 : Volley依赖库 Gson依赖库


参考文章:

Android Volley完全解析(一),初识Volley的基本用法

利用百度词典API和Volley网络库开发的android词典应用


你可能感兴趣的:(api,gson,baidu,Volley,aqi)