Android okhttp3 框架常用功能使用 4.1.0 版本

作者: android00 发布时间: 2019-08-22 浏览: 3774 次 编辑

本来是想围绕着HttpClient讲解的,后来发先Android4.4之后okhttp代替了hc,所以将不再讲解hc

okhttp的简单使用,主要包含:

  • 一般的get请求

  • 一般的post请求

  • 基于Http的文件上传

  • 文件下载

  • 加载图片

  • 支持请求回调,直接返回对象、对象集合

  • 支持session的保持

GitHub地址

OkHttp的GitHub地址是:OkHttp

依赖库导入

使用前需要先在项目中添加OkHttp的依赖库,在对应的Module的gradle中添加如下语句,目前最新应该是4.1.0

implementation("com.squareup.okhttp3:okhttp:4.1.0")

添加网络权限

<uses-permission android:name="android.permission.INTERNET"/>

一、GET请求

OkHttp支持同步和异步的网络请求,demo代码如下:

同步GET请求

public void httpSyncGetTest(){
    OkHttpClient okHttpClient = new OkHttpClient();
    //2.创建Request对象,设置一个url地址(百度地址),设置请求方式。
    Request request = new Request.Builder()
                  .url("http://www.niwoxuexi.com")
                  .get()
                  .build();
    //3.创建一个call对象,参数就是Request请求对象
    Call call = okHttpClient.newCall(request);
    //4.同步调用会阻塞主线程,这边在子线程进行
    new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //同步调用,返回Response,会抛出IO异常
                    Response response = call.execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
}

异步GET请求

public void httpAsyncGetTest(){
    //1.创建OkHttpClient对象
    OkHttpClient okHttpClient = new OkHttpClient();
    //2.创建Request对象,设置一个url地址(百度地址),设置请求方式。
    Request request = new Request.Builder()
          .url("http://www.baidu.com")
          .get()
          .build();
    //3.创建一个call对象,参数就是Request请求对象
    Call call = okHttpClient.newCall(request);
    //4.请求加入调度,重写回调方法
    call.enqueue(new Callback() {
        //请求失败执行的方法
        @Override
        public void onFailure(Call call, IOException e) {
            String err = e.getMessage().toString();
        }
        //请求成功执行的方法
        @Override
        public void onResponse(Call call, Response response) throws IOException {
              final String rtn = response.body().string();
              runOnUiThread(new Runnable() {
                @Override
                public void run() {
                }
              );
        }
    });
}

需要注意的是,异步调用的回调函数是在子线程当中的,因为需要用Handler或者runOnUiThread来更新UI


二、POST类型

在OkHttp中用Post方法向服务器发送一个请求体时,请求体需要是一个RequestBody。这个请求体可以是:

key-value:键值对类型
String:字符串类型
Form:类似于Html的表单数据提交
Stream:流类型
File:文件类型

三、Post 键值对

public void httpPostTest1(){
    //1.创建OkHttpClient对象
    OkHttpClient okHttpClient = new OkHttpClient();

    FormBody.Builder mBuild = new FormBody.Builder();
    mBuild.add("aa", "bb")
    .add("cc", 1);
    RequestBody requestBodyPost = mBuild.build();        

    //2.创建Request对象,设置一个url地址(百度地址),设置请求方式。
    Request request = new Request.Builder()
          .url("http://www.baidu.com")
          .post(requestBodyPost )
          .build();
    //3.创建一个call对象,参数就是Request请求对象
    Call call = okHttpClient.newCall(request);
    //4.请求加入调度,重写回调方法
    call.enqueue(new Callback() {
        //请求失败执行的方法
        @Override
        public void onFailure(Call call, IOException e) {
            String err = e.getMessage().toString();
        }
        //请求成功执行的方法
        @Override
        public void onResponse(Call call, Response response) throws IOException {
              final String rtn = response.body().string();
              //获取返回码
              final String code = String.valueOf(response.code())
              runOnUiThread(new Runnable() {
                @Override
                public void run() {
                }
              );
        }
    });
}

四、Post 字符串

有时候我们会有要传送字符串的需要,比如向服务器发送一个JSON字符串。那么就可以用如下方法:

public void httpPostTest1(){
    //1.创建OkHttpClient对象
    OkHttpClient okHttpClient = new OkHttpClient();
    //RequestBody中的MediaType指定为纯文本,编码方式是utf-8
    RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"),
            "{username:admin;password:admin}");
    //2.创建Request对象,设置一个url地址(百度地址),设置请求方式。
    Request request = new Request.Builder()
          .url("http://www.niwoxuexi.com")
          .post(requestBody )
          .build();
    //3.创建一个call对象,参数就是Request请求对象
    Call call = okHttpClient.newCall(request);
    //4.请求加入调度,重写回调方法
    call.enqueue(new Callback() {
        //请求失败执行的方法
        @Override
        public void onFailure(Call call, IOException e) {
            String err = e.getMessage().toString();
        }
        //请求成功执行的方法
        @Override
        public void onResponse(Call call, Response response) throws IOException {
              final String rtn = response.body().string();
              //获取返回码
              final String code = String.valueOf(response.code())
              runOnUiThread(new Runnable() {
                @Override
                public void run() {
                }
              );
        }
    });
}

也可以直接Post Json数据

public void httpPostTest2(){
    //1.创建OkHttpClient对象
     public  MediaType JSON = MediaType.parse("application/json; charset=utf-8");
     OkHttpClient client = new OkHttpClient();
     RequestBody body = RequestBody.create(JSON, json);
     //2.创建Request对象,设置一个url地址, 设置请求方式。
     Request request = new Request.Builder()
      .url("http://www.niwoxuexi.com")
      .post(body)
      .build();

    //3.创建一个call对象,参数就是Request请求对象
    Call call = okHttpClient.newCall(request);
    //4.请求加入调度,重写回调方法
    call.enqueue(new Callback() {
        //请求失败执行的方法
        @Override
        public void onFailure(Call call, IOException e) {
            String err = e.getMessage().toString();
        }
        //请求成功执行的方法
        @Override
        public void onResponse(Call call, Response response) throws IOException {
              final String rtn = response.body().string();
              //获取返回码
              final String code = String.valueOf(response.code())
              runOnUiThread(new Runnable() {
                @Override
                public void run() {
                }
              );
        }
    });
}

五、Post提交表单

public void httpPostTest3(){
    //1.创建OkHttpClient对象
     OkHttpClient client = new OkHttpClient();
     MultipartBody.Builder mBuild = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("username", "xxx")
            .addFormDataPart("password", "xxx");
     //2.创建Request对象,设置一个url地址, 设置请求方式。
    RequestBody requestBody= mBuild.build();       
        final Request request = new Request.Builder()
                .url("http://www.niwoxuexi.com/")
                .post(requestBody)
                .build();

    //3.创建一个call对象,参数就是Request请求对象
    Call call = okHttpClient.newCall(request);
    //4.请求加入调度,重写回调方法
    call.enqueue(new Callback() {
        //请求失败执行的方法
        @Override
        public void onFailure(Call call, IOException e) {
            String err = e.getMessage().toString();
        }
        //请求成功执行的方法
        @Override
        public void onResponse(Call call, Response response) throws IOException {
              final String rtn = response.body().string();
              //获取返回码
              final String code = String.valueOf(response.code())
              runOnUiThread(new Runnable() {
                @Override
                public void run() {
                }
              );
        }
    });
}

六、Post提交多文件

public void httpPostTest4(){
    //1.创建OkHttpClient对象
    OkHttpClient http = new OkHttpClient();
    MultipartBody.Builder mBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
    int i = 0;
    for(String filePath :filelist) {
        File file = new File(filePath);
        if (!file.exists()){
            Toast.makeText(MainActivity.this,"上传"+filePath+"文件不存在!", Toast.LENGTH_SHORT).show();
            continue;
        }
        String  fileMimeType = getMimeType(file);
        //这里获取文件类型,方法自己定义
        MediaType mediaType = MediaType.parse(fileMimeType);
        RequestBody fileBody = RequestBody.create(mediaType, file);
        mBody.addFormDataPart("file" + i, file.getName(), fileBody);
        i++;
    }
    //2.创建Request对象,设置一个url地址, 设置请求方式。
    RequestBody requestBody = mBody.build();
    Request requestPostFile = new Request.Builder()
                .url("http://www.niwoxuexi.com/")
                .post(requestBody)
                .build();

    //3.创建一个call对象,参数就是Request请求对象
    Call call = okHttpClient.newCall(request);
    //4.请求加入调度,重写回调方法
    call.enqueue(new Callback() {
        //请求失败执行的方法
        @Override
        public void onFailure(Call call, IOException e) {
            String err = e.getMessage().toString();
        }
        //请求成功执行的方法
        @Override
        public void onResponse(Call call, Response response) throws IOException {
              final String rtn = response.body().string();
              //获取返回码
              final String code = String.valueOf(response.code())
              runOnUiThread(new Runnable() {
                @Override
                public void run() {
                }
              );
        }
    });
}

android获取文件getMimeType的方法

 private static String getSuffix(File file) {  
        if (file == null || !file.exists() || file.isDirectory()) {  
            return null;  
        }  
        String fileName = file.getName();  
        if (fileName.equals("") || fileName.endsWith(".")) {  
            return null;  
        }  
        int index = fileName.lastIndexOf(".");  
        if (index != -1) {  
            return fileName.substring(index + 1).toLowerCase(Locale.US);  
        } else {  
            return null;  
        }  
}  

public static String getMimeType(File file){  
      String suffix = getSuffix(file);  
        if (suffix == null) {  
            return "file/*";  
        }  
        String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(suffix);  
        if (type != null || !type.isEmpty()) {  
            return type;  
        }  
        return "file/*";  
}

同时上传文件加上键值对参数的方法:

RequestBody multipartBody = new MultipartBody.Builder()
    .setType(MultipartBody.ALTERNATIVE)
    .addFormDataPart("aa","bb")
    .addFormDataPart("cc",1)
    .addFormDataPart("file",filename,fileBody)*/
    .build();

七、下载图片

public void httpDownloadImage(){
    OkHttpClient client = new OkHttpClient();
    final Request request = new Request
            .Builder()
            .get()
            .url("http://avatar.csdn.net/B/0/1/1_new_one_object.jpg")
            .build();
    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            ToastUtil.showToast(DownImageActivity.this, "下载图片失败");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            InputStream inputStream = response.body().byteStream();
            //将图片显示到ImageView中
            final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    iv_result.setImageBitmap(bitmap);
                }
            });
            //将图片保存到本地存储卡中
            File file = new File(Environment.getExternalStorageDirectory(), "image.png");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            byte[] temp = new byte[128];
            int length;
            while ((length = inputStream.read(temp)) != -1) {
                fileOutputStream.write(temp, 0, length);
            }
            fileOutputStream.flush();
            fileOutputStream.close();
            inputStream.close();
        }
    });
}

指定图片地址并下载成功后,获取图片的输入流,先用Bitmap decodeStream(InputStream is)方法将输入流转为Bitmap然后显示出来,然后将图片保存到本地存储卡根目录下
记得要申请存储卡的写权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />