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

android volley get请求使用

程序员文章站 2022-04-10 15:31:38
调用百度api微博热门精选接口,使用了volley,简单说说volley get的请求方式的使用 header的设置和请求参数的设置,见代码如下: ......

调用百度api微博热门精选接口,使用了volley,简单说说volley get的请求方式的使用

header的设置和请求参数的设置,见代码如下:

 private void getWeixinNews() {
        StringBuilder sb = new StringBuilder();
        try {
            sb.append("?num=").append(10).append("&rand=").append(1).append("&word=").append((URLEncoder.encode("西游记","UTF-8")).toString()).
                    append("&page=").append(1).append("&src=").append((URLEncoder.encode("人民日报","UTF-8")).toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        stringRequest = new StringRequest(Request.Method.GET, "http://apis.baidu.com/txapi/weixin/wxhot"+sb.toString(), new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d("TAG", response);
                parseJson(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage(), error);
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Charset", "UTF-8");
                headers.put("Content-Type", "application/x-javascript");
                headers.put("Accept-Encoding", "gzip,deflate");
                headers.put("apikey", "f8072b317a936623251258810df09d4e");
                return headers;
            }

        };
    }

    private void parseJson(String response) {
        Gson gson = new Gson();
        BigWeiXin bigWeiXin = gson.fromJson(response, BigWeiXin.class);
        List<WeiXin> newslist = bigWeiXin.getNewslist();
        for (WeiXin weixin : newslist) {
            Log.d("TAG", "ctime is " + weixin.getCtime());
            Log.d("TAG", "title is " + weixin.getTitle());
            Log.d("TAG", "description is " + weixin.getDescription());
            Log.d("TAG", "picUrl is " + weixin.getPicUrl());
            Log.d("TAG", "url is " + weixin.getUrl());
        }
    }