首页 > android 如何使用 volley 实现 百度的api 连接(带key)?

android 如何使用 volley 实现 百度的api 连接(带key)?

做一个简单的查询app(学校作业),比如查天气,网上搜了api接口,想使用百度提供的,
api介绍网址"http://apistore.baidu.com/apiworks/servicedetail/478.html",按要求注册取得了key;之前按照搜的教程学习了volley: "http://blog.csdn.net/guolin_blog/article/details/17482095",想使用JsonObjectRequest实现需求,但不知怎么使用volley实现百度带key的api请求,急!


百度天气api要求把key放到请求的header里,我想你的疑问主要在如何设置header。volley设置header需要重写Request的getHeaders方法,以下是获取北京天气简单的示例。

String url = "http://apis.baidu.com/heweather/weather/free?city=beijing"
JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        //处理正常的返回结果
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //处理异常的返回结果
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                //添加百度apikey
                headers.put("apikey", "your apikey");
                return headers;
            }
};
RequestQueue mQueue = Volley.newRequestQueue(context);
mQueue.add(jsonObjRequest);
mQueue.start();
【热门文章】
【热门文章】