Android--android okhttp3.0 框架使用总结

最近工作主要用到OkHttp3.0网络请求框架,进行Get请求,Post请求,多文件上传等功能,本文内容大部分来源于网上博文,仅做个人总结记录

以下内容来源其他博文:
在使用OKHttp之前,首先要先了解如下几个比较核心的类:

OkHttpClient:客户端对象
Request:访问请求,Post请求中需要包含RequestBody
RequestBody:请求数据,在Post请求中用到
Response:即网络请求的响应结果
MediaType:数据类型,用来表明数据是json,image,pdf等一系列格式
client.newCall(request).execute():同步的请求方法
client.newCall(request).enqueue(Callback callBack):异步的请求方法,但Callback是执行在子线程中的,因此不能在此进行UI更新操作

GitHub地址

OkHttp的GitHub地址是:OkHttp
OkIo的GitHub地址是:OkIo

依赖库导入

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

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

此外,OkHttp内部以来另外一个开源库Oklo

compile 'com.squareup.okio:okio:1.12.0'

添加网络权限

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

一、GET请求

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

同步GET请求

        //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.同步调用会阻塞主线程,这边在子线程进行
        new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //同步调用,返回Response,会抛出IO异常
                        Response response = call.execute();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

异步GET请求

        //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 键值对

        //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字符串。那么就可以用如下方法:

        //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.baidu.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 static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
     OkHttpClient client = new OkHttpClient();
     RequestBody body = RequestBody.create(JSON, json);
     Request request = new Request.Builder()
      .url("http://www.baidu.com")
      .post(body)
      .build();
      ...

五、Post提交表单

        OkHttpClient client = new OkHttpClient();
        MultipartBody.Builder mBuild = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("username", "xxx")
                .addFormDataPart("password", "xxx");
        RequestBody requestBody= mBuild.build();       
        final Request request = new Request.Builder()
                .url("http://www.jianshu.com/")
                .post(requestBody)
                .build();
        ...

六、Post提交多文件

        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++;
        }
        RequestBody requestBody = mBody.build();
        Request requestPostFile = new Request.Builder()
                .url("http://www.jianshu.com/")
                .post(requestBody)
                .build();
         ...

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();

七、下载图片

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" />

参考博文

Android OkHttp的基本用法
Android 网络编程之最新OKHTTP:3.9.0
android获取文件getMimeType的方法



作者:某杰
链接:https://www.jianshu.com/p/bb57bc65e4ce
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

发布了7 篇原创文章 · 获赞 69 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/u014320421/article/details/105217333
今日推荐