Android网络请求框架的使用okhttp

        1、在manifest文件中添加网络权限。

android:name="android.permission.INTERNET"/>
        2、在module的build.gradle文件中添加依赖库。

compile 'com.squareup.okhttp:okhttp:2.0.0'
compile 'com.squareup.okio:okio:1.5.0'
        3、使用okhttp请求网络字符串。

private void okhttpRequestString () {
    //创建OkHttpClient对象
    OkHttpClient okHttpClient = new OkHttpClient ();
    //定义url字符串。
    String url = "https://www.baidu.com";
    //构建请求对象
    Request request = new Request.Builder ().url (url).build ();
    //发送请求。
    Call call = okHttpClient.newCall (request);
    //设置回调
    call.enqueue (new Callback () {
        //请求失败
        @Override
        public void onFailure (Request request, IOException e) {
            Log.d ("ysy","request is failure!");
        }
        //请求成功
        @Override
        public void onResponse (Response response) throws IOException {
            //获取请求到的数据
            String string = response.body ().string ();
            //发送Handler消息,跟新UI
            Message msg = new Message ();
            msg.what = MSG_STRING;
            msg.obj = string;
            mHandler.sendMessage (msg);
        }
    });
}
       4、使用okhttp从网络上请求一张图片。

private void okhttpRequestImage () {
    //创建OkHttpClient对象
    OkHttpClient okHttpClient = new OkHttpClient ();
    //定义url字符串。
    String url = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";
    //构建请求对象
    Request request = new Request.Builder ().url (url).build ();
    //发送请求。
    Call call = okHttpClient.newCall (request);
    //设置回调
    call.enqueue (new Callback () {
        //请求失败
        @Override
        public void onFailure (Request request, IOException e) {
            Log.d ("ysy","request image is failure!");
        }
        //请求成功
        @Override
        public void onResponse (Response response) throws IOException {
            //获取请求到的输入流
            InputStream inputStream = response.body ().byteStream ();
            //将输入流加载为一个Bitmap对象。
            Bitmap bitmap = BitmapFactory.decodeStream (inputStream);
            //发送Handler消息,跟新UI
            Message msg = new Message ();
            msg.what = MSG_IMAGE;
            msg.obj = bitmap;
            mHandler.sendMessage (msg);
        }
    });
}
       

你可能感兴趣的:(Android网络请求)