美文网首页
okhttp的简单使用

okhttp的简单使用

作者: 码农耕 | 来源:发表于2019-05-29 14:59 被阅读0次

1.在app的build.gradle中添加依赖库
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
2.在AndroidMainfest中添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
3.如果是新版本的还需要允许http请求(我这里是添加配置文件)
在AndroidMainfest中的application中添加
android:networkSecurityConfig="@xml/network_security_config"
network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>

4.简单使用

// 加载网路图片数据
private void loadDatas(int page) {
    // 创建一个请求体
    Request request = new Request.Builder().url(mUrl + page).build();
    OkHttpClient okHttpClient = new OkHttpClient();

    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.i("TAG", "加载错误 IOException=" + e.toString());
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException         {
            //如果响应成功
            if (response.isSuccessful()) {
                //获得响应体的结果
                String result = response.body().string();
                try {
                    JSONObject json = new JSONObject(result);
                    // 获得了一个array的几何
                    JSONArray array = new JSONArray(json.getString("results"));
                    // 看见几何或者数组 想要拿到里面的东西需要进行for循环
                    for (int i = 0; i < array.length(); i++) {
                        //获取一个json对象
                        JSONObject jsonObject = array.getJSONObject(i);
                        String urls = jsonObject.getString("url");
                        Log.e("tag", "========== url: " + urls);
                        mUrls.add(urls);
                    }
                    // 通过handle来到主线程修改Ui
                    mHandler.sendEmptyMessage(2);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }
    });

}

相关文章

网友评论

      本文标题:okhttp的简单使用

      本文链接:https://www.haomeiwen.com/subject/anrytctx.html