OkHttp使用总结

一 OkHttp介绍

OkHttp是一个优秀的网络请求框架,目前主流已经替换httpclient, HttpURLConnection 使用方式;

OkHttp支持连接同一地址的链接共享同一个socket,通过连接池来减小响应延迟,自带GZIP压缩,请求缓存等优势;

OkHttp 成为 Android 最常见的网络请求库, 但并不妨碍java后端学习他,所以这边知识追寻者 做了常用总结

github: https://github.com/square/okhttp

官方文档:https://square.github.io/okhttp/

二 依赖

目前最新版本:4.9.0

maven

<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>3.6.0</version>
</dependency>

gradle

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

三 GET 请求

请求步骤

  1. 获取OkHttpClient对象
  2. 设置请求request
  3. 封装call
  4. 异步调用,并设置回调函数
 /**
     * @Author lsc
     * <p>get 请求 </p>
     * @Param [url]
     * @Return
     */
    public void get(String url){
        // 1 获取OkHttpClient对象
        OkHttpClient client = new OkHttpClient();
        // 2设置请求
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        // 3封装call
        Call call = client.newCall(request);
        // 4异步调用,并设置回调函数
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // ...
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (response!=null && response.isSuccessful()){
                    // ...
                    // response.body().string();
                }
            }
        });
        //同步调用,返回Response,会抛出IO异常
        //Response response = call.execute();
    }

四 POST 请求

4.1 form 表单形式

  1. 获取OkHttpClient对象
  2. 构建参数body
  3. 构建 request
  4. 将Request封装为Call
  5. 异步调用
 /**
     * @Author lsc
     * <p> post 请求, form 参数</p>
     * @Param [url]
     * @Return
     */
    public void postFormData(String url){
        // 1 获取OkHttpClient对象
        OkHttpClient client = new OkHttpClient();
        // 2 构建参数
        FormBody formBody = new FormBody.Builder()
                .add("username", "admin")
                .add("password", "admin")
                .build();
        // 3 构建 request
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        // 4 将Request封装为Call
        Call call = client.newCall(request);
        // 5 异步调用
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // ...
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (response!=null && response.isSuccessful()){
                    // ...
                }
            }
        });
    }

4.2 json参数形式

  1. 获取OkHttpClient对象
  2. 构建参数
  3. 构建 request
  4. 将Request封装为Call
  5. 异步调用
/**
     * @Author lsc
     * <p>post 请求 ,json参数 </p>
     * @Param [url, json]
     * @Return
     */
    public void postForJson(String url, String json){
        // 1 获取OkHttpClient对象
        OkHttpClient client = new OkHttpClient();
        // 2 构建参数
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        // 3 构建 request
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        // 4 将Request封装为Call
        Call call = client.newCall(request);
        // 5 异步调用
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // ...
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (response!=null && response.isSuccessful()){
                    // ...
                }
            }
        });
    }

如果是json字符串,替换请求媒体类型即可

 // 2 构建参数
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), "{username:admin;password:admin}");
        // 3 构建 request
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

4.3 文件下载

  1. 获取OkHttpClient对象
  2. 构建 request
  3. 异步调用
  4. 文件下载
/**
     * @Author lsc
     * <p> 文件下载 </p>
     * @Param url 下载地址url
     * @Param target 下载目录
     * @Param target 文件名
     * @Return
     */
    private void download(String url, String target, String fileName){
        // 1 获取OkHttpClient对象
        OkHttpClient client = new OkHttpClient();
        // 2构建 request
        Request request = new Request.Builder()
                .url(url)
                .build();
        // 3 异步调用
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    // 4 文件下载
                    downlodefile(response, target,fileName);
                }
            }
        });
    }

    private void downlodefile(Response response, String url, String fileName) {
        InputStream inputStream = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream outputStream = null;
        try {
            inputStream = response.body().byteStream();
            //文件大小
            long total = response.body().contentLength();
            File file = new File(url, fileName);
            outputStream = new FileOutputStream(file);
            long sum = 0;
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

4.4 文件上传

  1. 获取OkHttpClient对象
  2. 封装参数以 form形式, 媒体格式为二进制流
  3. 封装 request
  4. 异步回调
/**
     * @Author lsc
     * <p> 文件上传 </p>
     * @Param [url]
     * @Return
     */
    public void upload(String url){
        File file = new File("C:/mydata/generator/test.txt");
        if (!file.exists()){
            System.out.println("文件不存在");
        }else{
            // 获取OkHttpClient对象
            OkHttpClient client = new OkHttpClient();
            // 2封装参数以 form形式
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("username", "admin")
                    .addFormDataPart("password", "admin")
                    .addFormDataPart("file", "555.txt", RequestBody.create(MediaType.parse("application/octet-stream"), file))
                    .build();
            // 3 封装 request
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            // 4 异步回调
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                }
            });
        }
    }

公众号知识追寻者,欢迎关注,获取原创PDF,面试题集
OkHttp使用总结

上一篇:OkHttp,一次无奈的使用


下一篇:OkHttpClient调优案例