Android 使用OKHttp获取字符串和下载图片

一、使用前需要添加依赖

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

附上GitHub上OKHttp的地址:OkHttp项目

AndroidManifest文件中需要添加网络使用权限


二、实例化OkHttpClient,用于发送请求

OkHttpClient client = new OkHttpClient();

三、建立相应的请求体

//get()方法表示请求的方式为GET,相应的也有post()方法
//url()方法传递url
//最后调用build()方法返回Request对象
Request request = new Request.Builder()
            .get()
            .url("https://www.baidu.com")
            .build();

四、发送请求

使用OkHttpClient发送Request请求

        //request为请求体
        //enqueue()方法中传递回调对象
        //enqueue()方法为异步网络请求,同样的,还可以使用execute()方法发送同步网络请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败时回调的方法
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功时回调的方法
                //response是返回的数据
                //如果获取的是图片资源
                //byte[] imageByte = response.body().bytes();
                //Bitmap bitmap = BitmapFactory.decodeByteArray(imageByte,0,imageByte.length);
                
                //如果获取的资源是字符串类型,可以直接调用以下方法
                String string = response.body().string();
            }
        });

你可能感兴趣的:(Android)