Okhttp的使用

1、github网址:https://github.com/square/okhttp

依赖 implementation 'com.squareup.okhttp3:okhttp:4.9.3'

2、使用过程

2.1、创建一个客户端,类似一个浏览器

OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();

2.2、创建请求的内容

Request request = new Request.Builder()
                .get()
                .url(BASE_URL + "get/text")
                .build();

2.3、用客户端去创建请求任务

Call task = okHttpClient.newCall(request);

2.4、进行异步请求即可

task.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                // 请求失败
                Log.d(TAG, "cfx task.enqueue onFailure: " + e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 请求成功
                    Log.d(TAG, "cfx task.enqueue 请求成功");
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        Log.d(TAG, "cfx responseBody = " + responseBody.string());
                    }
                }
            }
        });

后续为其他请求方式:

// 网络请求
    private void requestNetwork() {
        // 1.创建一个客户端,类似一个浏览器
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();
        // 2.创建请求的内容
        Request request = new Request.Builder()
                .get()
                .url(BASE_URL + "get/text")
                .build();
        // 3.用客户端去创建请求任务
        Call task = okHttpClient.newCall(request);
        // 4.进行异步请求
        task.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                // 请求失败
                Log.d(TAG, "cfx task.enqueue onFailure: " + e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 请求成功
                    Log.d(TAG, "cfx task.enqueue 请求成功");
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        Log.d(TAG, "cfx responseBody = " + responseBody.string());
                    }
                }
            }
        });
    }

    // post提交字符串
    private void postRequest() {
        // 1.创建一个客户端,类似一个浏览器
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();
        // 2.创建请求的内容
        CommentItem commentItem = new CommentItem("12345678", "这是使用okhttp提交的字符串");
        Gson gson = new Gson();
        String jsonStr = gson.toJson(commentItem);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody responseBody = RequestBody.create(jsonStr, mediaType);
        Request request = new Request.Builder()
                .url(BASE_URL + "post/comment")
                .post(responseBody)
                .build();
        // 3.用客户端去创建请求任务
        Call task = okHttpClient.newCall(request);
        // 4.进行异步请求
        task.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                // 请求失败
                Log.d(TAG, "cfx task.enqueue onFailure");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 请求成功
                    Log.d(TAG, "cfx task.enqueue 请求成功");
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        Log.d(TAG, "cfx responseBody = " + responseBody.string());
                    }
                }
            }
        });
    }

    // 带参数请求
    private void requestByParams() {
        Map<String, String> params = new HashMap<>();
        params.put("keyword", "这是okhttp的关键词keyword");
        params.put("page", "321");
        params.put("order", "0");
        startRequest(params, "GET", "get/param");
    }

    // post带参数请求
    private void postRequestByParams() {
        Map<String, String> params = new HashMap<>();
        params.put("string", "这是我提交的post带参数请求");
        startRequest(params, "POST", "post/string");
    }

    private void startRequest(Map<String, String> params, String method, String api) {
        // 1.创建一个客户端,类似一个浏览器
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();
        // 2.创建请求的内容
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("?");
        Iterator<Map.Entry<String, String>> entryIterator = params.entrySet().iterator();
        while (entryIterator.hasNext()) {
            Map.Entry<String, String> next = entryIterator.next();
            stringBuilder.append(next.getKey());
            stringBuilder.append("=");
            stringBuilder.append(next.getValue());
            if (entryIterator.hasNext()) {
                stringBuilder.append("&");
            }
        }
        String url = BASE_URL + api + stringBuilder.toString();
        Log.d(TAG, "cfx url = " + url);
        Request request = null;
        if ("GET".equals(method)) {
            request = new Request.Builder()
                    .get()
                    .url(url)
                    .build();
        } else if ("POST".equals(method)) {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody requestBody = RequestBody.create("string=这是我提交的post带参数请求2", mediaType);
            request = new Request.Builder()
                    .post(requestBody)
                    .url(url)
                    .build();
        }
        // 3.用客户端去创建请求任务
        Call task = okHttpClient.newCall(request);
        // 4.进行异步请求
        task.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                // 请求失败
                Log.d(TAG, "cfx task.enqueue onFailure");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 请求成功
                    Log.d(TAG, "cfx 请求成功");
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        Log.d(TAG, "cfx responseBody.string() = " + responseBody.string());
                    }
                }
            }
        });

    }

    // 上传文件
    private void uploadFile() {
        // 1.创建一个客户端,类似一个浏览器
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();
        // 2.创建请求的内容
        File file = new File("/storage/self/primary/DCIM/Camera/20200130_101215.jpg");
        if(!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                Log.d(TAG, " IOException " + e);
            }
        }
        MediaType fileType = MediaType.parse("image/jpeg");
        RequestBody fileBody = RequestBody.create(file, fileType);
        RequestBody requestBody = new MultipartBody.Builder()
                .addFormDataPart("file", file.getName(), fileBody)
                .build();

        Request request = new Request.Builder()
                .post(requestBody)
                .url(BASE_URL + "file/upload")
                .build();
        // 3.用客户端去创建请求任务
        Call task = okHttpClient.newCall(request);
        // 4.进行异步请求
        task.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                // 请求失败
                Log.d(TAG, "cfx uploadFile IOException: " + e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 请求成功
                    Log.d(TAG, "cfx uploadFile 请求成功");
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        Log.d(TAG, "cfx responseBody.string() = " + responseBody.string());
                    }
                }
            }
        });
    }

    // post上传多个文件
    private void uploadFileMore() {
        // 1.创建一个客户端,类似一个浏览器
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();
        // 2.创建请求的内容
        File file1 = new File("/storage/self/primary/DCIM/Camera/20200130_101215.jpg");
        File file2 = new File("/storage/self/primary/DCIM/Camera/20201030_153627.jpg");
        File file3 = new File("/storage/self/primary/DCIM/Camera/20210214_204403.jpg");
        if(!file1.exists()) {
            try {
                file1.createNewFile();
            } catch (IOException e) {
                Log.d(TAG, " IOException " + e);
            }
        }
        if(!file2.exists()) {
            try {
                file2.createNewFile();
            } catch (IOException e) {
                Log.d(TAG, " IOException " + e);
            }
        }
        if(!file3.exists()) {
            try {
                file3.createNewFile();
            } catch (IOException e) {
                Log.d(TAG, " IOException " + e);
            }
        }
        MediaType fileType = MediaType.parse("image/jpeg");
        RequestBody fileBody1 = RequestBody.create(file1, fileType);
        RequestBody fileBody2 = RequestBody.create(file2, fileType);
        RequestBody fileBody3 = RequestBody.create(file3, fileType);
        RequestBody requestBody = new MultipartBody.Builder()
                .addFormDataPart("files", file1.getName(), fileBody1)
                .addFormDataPart("files", file2.getName(), fileBody2)
                .addFormDataPart("files", file3.getName(), fileBody3)
                .build();
        Request request = new Request.Builder()
                .post(requestBody)
                .url(BASE_URL + "files/upload")
                .build();
        // 3.用客户端去创建请求任务
        Call task = okHttpClient.newCall(request);
        // 4.进行异步请求
        task.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                // 请求失败
                Log.d(TAG, "cfx uploadFileMore IOException: " + e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 请求成功
                    Log.d(TAG, "cfx uploadFileMore 请求成功");
                    ResponseBody responseBody = response.body();
                    if (responseBody != null) {
                        Log.d(TAG, "cfx responseBody.string() = " + responseBody.string());
                    }
                }
            }
        });
    }

    // 下载文件
    private void downloadFile() {
        // 1.创建一个客户端,类似一个浏览器
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();
        // 2.创建请求的内容
        Request request = new Request.Builder()
                .get()
                .url(BASE_URL + "download/15")
                .build();
        // 3.用客户端去创建请求任务
        Call task = okHttpClient.newCall(request);
        // 4.进行异步请求
        task.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                // 请求失败
                Log.d(TAG, "cfx downloadFile IOException: " + e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                int responseCode = response.code();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    Log.d(TAG, "cfx downloadFile 请求成功");
                    Headers headers = response.headers();
                    // for (Pair<? extends String, ? extends String> header : headers) {
                    //     Log.d(TAG, "cfx header.toString() = " + header.toString());
                    //     Log.d(TAG, "cfx header.component2() = " + header.component2());
                    // }
                    String headerField = headers.get("Content-disposition");
                    // 拿到下载的图片名称
                    String fileName = headerField.replace("attachment; filename=", "");
                    Log.d(TAG, "cfx fileName = " + fileName);
                    // 保存到 /storage/self/primary/DCIM/Camera/路径下面
                    String filePath = "/storage/self/primary/DCIM/Camera/" + fileName;
                    Log.d(TAG, "cfx filePath = " + filePath);
                    File file = new File(filePath);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
                    InputStream inputStream = response.body().byteStream();
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
                    int len;
                    byte[] buffer = new byte[1024];
                    while ((len = bufferedInputStream.read(buffer, 0, buffer.length)) != -1) {
                        bufferedOutputStream.write(buffer, 0, len);
                    }
                    bufferedOutputStream.flush();
                    CloseIo.CloseIoStream(bufferedOutputStream);
                    CloseIo.CloseIoStream(bufferedInputStream);
                }
            }
        });
    }

    // 下载文件, 方法2
    private void downloadFile2() {
        // 1.创建一个客户端,类似一个浏览器
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .build();
        // 2.创建请求的内容
        Request request = new Request.Builder()
                .get()
                .url(BASE_URL + "download/1")
                .build();
        // 3.用客户端去创建请求任务
        final Call task = okHttpClient.newCall(request);
        // 4.进行请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                InputStream inputStream = null;
                FileOutputStream fileOutputStream = null;
                try {
                    Response execute = task.execute();
                    Headers headers = execute.headers();
                    for (int i = 0; i < headers.size(); i++) {
                        String key = headers.name(i);
                        String value = headers.value(i);
                        Log.d(TAG, "cfx " + key + ": " + value);
                    }
                    String contentType = headers.get("Content-Type");
                    String headerField = headers.get("Content-disposition");
                    // 拿到下载的图片名称
                    String fileName = headerField.replace("attachment; filename=", "");
                    Log.d(TAG, "cfx fileName = " + fileName);
                    // 保存到 /storage/self/primary/DCIM/Camera/路径下面
                    String filePath = "/storage/self/primary/DCIM/Camera/" + fileName;
                    Log.d(TAG, "cfx filePath = " + filePath);
                    File file = new File(filePath);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    fileOutputStream = new FileOutputStream(file);
                    if (execute.body() != null) {
                        inputStream = execute.body().byteStream();
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
                            fileOutputStream.write(buffer, 0, len);
                        }
                        fileOutputStream.flush();
                    }
                } catch (IOException e) {
                    Log.d(TAG, "cfx run IOException: " + e);
                } finally {
                    CloseIo.CloseIoStream(fileOutputStream);
                    CloseIo.CloseIoStream(inputStream);
                }
            }
        }).start();
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值