温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

okhttp的get访问(加header)

发布时间:2020-06-24 15:52:58 来源:网络 阅读:808 作者:cai1449074828 栏目:开发技术

使用okhttp来调用百度提供的频道新闻API(http://apistore.baidu.com/apiworks/servicedetail/688.html)


okhttp的添加源

compile 'com.squareup.okhttp3:okhttp:3.2.0'


 String httpUrl = String httpArg = String requestString=requestString=httpUrl++httpArgrequest(requestString)

   

public void request(String requestString) {
    OkHttpClient mOkHttpClient=new OkHttpClient();
    Request.Builder requestBuilder = new Request.Builder().url(requestString).addHeader("apikey","592e46b62cfe201c68bf7d9f18db11ee");
    //可以省略,默认是GET请求
    requestBuilder.method("GET",null);
    Request request = requestBuilder.build();
    Call mcall= mOkHttpClient.newCall(request);
    mcall.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            System.out.println("失败");
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    swipeRefreshLayout.setRefreshing(false);
                }
            });
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (null != response.cacheResponse()) {
                String str = response.cacheResponse().toString();
                Log.i("wangshu", "cache---" + str);
            } else {
                String string=response.body().string().toString();
                System.out.println(string);
                try {
                    System.out.println(1);
                    JSONObject jsonObject=new JSONObject(string);
                    JSONArray jsonArray=jsonObject.getJSONObject("showapi_res_body").getJSONObject("pagebean").getJSONArray("contentlist");
                    for (int i=0;i<=9;i++){
                        XinWenBean xinWenBean=new XinWenBean();
                        xinWenBean.setTitle(jsonArray.getJSONObject(i).getString("title"));
                        xinWenBeanList.add(xinWenBean);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String str = response.networkResponse().toString();
                Log.i("wangshu", "network---" + str);
            }
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    swipeRefreshLayout.setRefreshing(false);
                    recyclerView.setAdapter(new XinWenRecyclerViewAdapter(getActivity(),xinWenBeanList));
                }
            });
        }
    });
}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI