okhttp3使用-基础篇

前言

在很长一段时间里,我一直使用HttpClient这个库进行网络请求的处理。这个库的版本经历了相当大的历史变迁,而且往往存在诸多的BUG。

我们一起来回顾下HttpClient的的历史,HttpClient项目开始于2001年,它是作为 Jakarta Commons的一个子项目。虽然该项目在2005年被HttpComponents项目所取代,也就是开始了HttpClient 3.x时代。在2007年的时候HttpComponents成为了Apache的顶级项目。而且该项目分裂成两个模块:HttpClient 和 HttpCore 。所以项目的维护者也是看到该库的一些不足所以在不停的更替版本。这样就导致一个问题,各种项目的版本混乱,而且其API也是不兼容,甚至存在使用可能会存在内存泄露的重大BUG版本。

相信通过本系列文章,你也许会在新的项目中尝试使用现代化的设计更为简洁的okhttp3进行网络相关的开发。

okhttp3概览

首先贴上项目地址:http://square.github.io/okhttp/,如果对源码感兴趣可以fork一份进行学习。该项目star有27k+,确实算是不少。主要还是其对android的高可用性和socket复用,非常适合移动端的开发,但是对于web端的Java应用开发也是同样的强大。

其主要特性如下:

  • 支持HTTP/2以及SPDY协议,允许所有同一个主机地址的请求共享同一个socket连接
  • 使用连接池可以缩短请求延时
  • 自带GZIP压缩减少响应数据的大小
  • 缓存响应内容,避免一些完全重复的请求

其核心主要有路由、连接协议、拦截器、代理、安全性认证、连接池以及网络适配,拦截器主要是指添加,移除或者转换请求或者回应的头部信息,总流程图如下:

注:图片来自网络,侵权即删

这个流程主要是通过Diapatcher不断从RequestQueue中取出请求(Call),根据是否已缓存从内存缓存或是服务器取得请求的数据,其具体实现细节以后再单独撰文讨论。

兼容性

  • Android 2.3+
  • Java1.7

如果你的项目还在使用Java1.6的话赶紧升级JDK吧。

基本使用

okhttp3支持同步和异步请求,如果不想堵塞调用线程我们一般使用异步请求,在Callback中获取请求返回结果再进一步处理。

请求操作一般都有一个套路:

构造OkHttpClient(可以通过new或者Builder)->构造Request->newCall->Call#execute或者Call#enqueue。最后一步操作就是同步或者异步请求的区别。

发送GET请求

同步请求的实例代码如下:

/**
 * 同步GET请求
 * -OkHttpClient#Builder构造客户端对象;
 * -构造Request对象;
 * -通过前两步中的对象构建Call对象;
 * -通过Call#execute(Callback)方法来提交异步请求;
 */
@Test
public void syncGetCall() throws IOException {
    OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
    final Request request = new Request.Builder()
            .url(url)
            .get()//默认就是GET请求,可以不写
            .build();
    Call call = okHttpClient.newCall(request);
    Response response = call.execute();
    logger.debug(response.body().string());
}

异步请求实例代码如下:

/**
 * 异步GET请求
 * -OkHttpClient#Builder构造客户端对象;
 * -构造Request对象;
 * -通过前两步中的对象构建Call对象;
 * -通过Call#enqueue(Callback)方法来提交异步请求;
 */
@Test
public void asyncGetCall() throws Exception{
    OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();;
    final Request request = new Request.Builder()
            .url(url)
            .get()//默认就是GET请求,可以不写
            .build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            logger.error("onFailure: ");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            logger.debug("onResponse: " + response.body().string());
        }
    });
    //等待请求线程,否则主线程结束无法看到请求结果
    Thread.currentThread().join(5000);
}

异步操作的时候主线程必须要调用join,否则请求还没处理玩线程就退出看不到打印信息。

发送POST请求

post和get最大的区别局势post请求需要构造一个RequestBody对象来填充需要发送的数据。我们来看他的创建方法:

从create 方法签名就可以看出,它支持发送stirng,字节流和文件。下面对各种数据发送进行举例。

提交String数据

/**
 * post发送String数据
 * 这里使用github的markdown编辑器API,我们发送一个文本,编辑器会返回格式化富文本信息
 */
@Test
public void postStringTest() throws InterruptedException {
    MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
    String requestBody = "hello github";
    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(mediaType, requestBody))
            .build();
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            logger.debug("onFailure: " + e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            logger.debug(response.protocol() + " " + response.code() + " " + response.message());
            Headers headers = response.headers();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < headers.size(); i++) {
                sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
            }
            logger.debug("headers:\n{}",sb.toString());
            logger.debug("onResponse: " + response.body().string());
        }
    });
    Thread.currentThread().join(5000);
}

返回结果:

11:21:08.385 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - http/1.1 200 OK
11:21:08.389 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - headers:
Date:Tue, 10 Jul 2018 03:21:09 GMT
Content-Type:text/html;charset=utf-8
Transfer-Encoding:chunked
Server:GitHub.com
Status:200 OK
X-RateLimit-Limit:60
X-RateLimit-Remaining:52
X-RateLimit-Reset:1531194293
X-CommonMarker-Version:0.17.4
Access-Control-Expose-Headers:ETag, Link, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
Access-Control-Allow-Origin:*
Strict-Transport-Security:max-age=31536000; includeSubdomains; preload
X-Frame-Options:deny
X-Content-Type-Options:nosniff
X-XSS-Protection:1; mode=block
Referrer-Policy:origin-when-cross-origin, strict-origin-when-cross-origin
Content-Security-Policy:default-src'none'
X-Runtime-rack:0.022042
Vary:Accept-Encoding
X-GitHub-Request-Id:08AC:05AB:1776494:1F2723C:5B442624

11:21:08.392 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - onResponse: <p>hello github</p>

最终返回了<p>hello github</p>,说明我们的请求发送成功了。注意这里是异步发送POST请求,同样需要再主线程执行Thread.currentThread().join();

提交字节流

/**
 * 发送字节流
 * 可以使用create方法或者重载RequestBody进行自定义构造
 * @throws InterruptedException
 * @throws UnsupportedEncodingException
 */
@Test
public void postBytesTest() throws InterruptedException, UnsupportedEncodingException {
    RequestBody requestBody = new RequestBody() {
        @Nullable
        @Override
        public MediaType contentType() {
            return MediaType.parse("text/x-markdown; charset=utf-8");
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8("你好,github");
        }
    };
    //requestBody = RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), "你好,github".getBytes("utf-8"));
    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(requestBody)
            .build();
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            logger.debug("onFailure: " + e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            logger.debug(response.protocol() + " " + response.code() + " " + response.message());
            Headers headers = response.headers();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < headers.size(); i++) {
                sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
            }
            logger.debug("headers:\n{}", sb.toString());
            logger.debug("onResponse: " + response.body().string());
        }
    });
    Thread.currentThread().join(5000);
}

返回结果:

11:32:52.421 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - http/1.1 200 OK
11:32:52.424 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - headers:
Date:Tue, 10 Jul 2018 03:32:54 GMT
Content-Type:text/html;charset=utf-8
Transfer-Encoding:chunked
Server:GitHub.com
Status:200 OK
X-RateLimit-Limit:60
X-RateLimit-Remaining:47
X-RateLimit-Reset:1531194293
X-CommonMarker-Version:0.17.4
Access-Control-Expose-Headers:ETag, Link, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
Access-Control-Allow-Origin:*
Strict-Transport-Security:max-age=31536000; includeSubdomains; preload
X-Frame-Options:deny
X-Content-Type-Options:nosniff
X-XSS-Protection:1; mode=block
Referrer-Policy:origin-when-cross-origin, strict-origin-when-cross-origin
Content-Security-Policy:default-src'none'
X-Runtime-rack:0.026395
Vary:Accept-Encoding
X-GitHub-Request-Id:0B55:5D3F:C0CE72:1032A20:5B4428E4

11:32:52.426 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - onResponse: <p>你好,github</p>

注意,上边RequestBody也可以自己重载实现。

提交文件

/**
 * 发送文件
 * @throws InterruptedException
 */
@Test
public void postFileTest() throws InterruptedException {
    MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
    OkHttpClient okHttpClient = new OkHttpClient();
    File file = new File("D:\\code\\work\\egovaCloud\\src\\test\\java\\test.md");
    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(mediaType, file))
            .build();
    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            logger.debug("onFailure: " + e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            logger.debug(response.protocol() + " " + response.code() + " " + response.message());
            Headers headers = response.headers();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < headers.size(); i++) {
                sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
            }
            logger.debug("headers:\n{}", sb.toString());
            logger.debug("onResponse: " + response.body().string());
        }
    });
    Thread.currentThread().join(5000);
}

返回结果:

11:43:56.177 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - http/1.1 200 OK
11:43:56.180 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - headers:
Date:Tue, 10 Jul 2018 03:43:57 GMT
Content-Type:text/html;charset=utf-8
Transfer-Encoding:chunked
Server:GitHub.com
Status:200 OK
X-RateLimit-Limit:60
X-RateLimit-Remaining:43
X-RateLimit-Reset:1531194293
X-CommonMarker-Version:0.17.4
Access-Control-Expose-Headers:ETag, Link, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval
Access-Control-Allow-Origin:*
Strict-Transport-Security:max-age=31536000; includeSubdomains; preload
X-Frame-Options:deny
X-Content-Type-Options:nosniff
X-XSS-Protection:1; mode=block
Referrer-Policy:origin-when-cross-origin, strict-origin-when-cross-origin
Content-Security-Policy:default-src'none'
X-Runtime-rack:0.025442
Vary:Accept-Encoding
X-GitHub-Request-Id:0E27:0259:C79992:108ADDE:5B442B7B

11:43:56.183 [OkHttp https://api.github.com/...] DEBUG OkHttpTest - onResponse: <h2>
<a id="user-content-hello-github" class="anchor" href="#hello-github" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>hello github</h2>提交表单

提交表单

/**
 * post提交表单,使用FormBody来构造表单键值对
 */
@Test
public void postFormDataTest() throws InterruptedException {
    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new FormBody.Builder()
            .add("search", "java")
            .build();
    Request request = new Request.Builder()
            .url("https://en.wikipedia.org/w/index.php")
            .post(requestBody)
            .build();

    okHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            logger.debug("onFailure: " + e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            logger.debug(response.protocol() + " " + response.code() + " " + response.message());
            Headers headers = response.headers();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < headers.size(); i++) {
                sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
            }
            logger.debug("headers:\n{}", sb.toString());
            logger.debug("onResponse: " + 
response.body().string());
        }
    });
    Thread.currentThread().join(5000);
}

这里是向 wiki网站发起关键字搜索,因为返回结果太长不在此展示返回结果。

数据分块传输

使用MutipartBody可以进行分块传输,每个块都可以自定义Header,比如我们需要传送一个图片并且需要携带额外的信息,则可以自己构建下面的请求:

/**
 * 上传文件同时写到额外表单参数
 * @throws Exception
 */
@Test
public void postMutilPartFormData() throws Exception{
    MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("extra", "extra args")
            .addFormDataPart("file", "logo.png",
                    RequestBody.create(MEDIA_TYPE_PNG, new File("D:\\code\\work\\egovaCloud\\src\\main\\resources\\static\\image\\logo.png")))
            .build();
    Request request = new Request.Builder()
            .url("http://localhost:8888/base-platform/upload/uploadFile")
            .post(requestBody)
            .build();
    OkHttpClient client = new OkHttpClient();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    logger.debug(response.body().string());
}

addFormDataPart这个方法其实是下面方法的缩写:

.addPart(
         Headers.of("Content-Disposition", "form-data; name=\"extra\""),
         RequestBody.create(null, "Square Logo"))

这样我们就不需要单独去设置这个头部信息。

在后端我们使用spring的MultipartHttpServletRequest就可以后去额外的参数,实例代码如下:

package cn.com.egova.baseplatform.controller;

import cn.com.egova.baseplatform.enums.ResultCode;
import cn.com.egova.baseplatform.util.ResultUtils;
import io.swagger.annotations.Api;
import org.activiti.engine.impl.persistence.StrongUuidGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * 客户端文件上传
 * Created by gxf on 17-5-26.
 */
@Controller
@RequestMapping(value ="/upload")
@Api(tags = "文件上传模块")
public class FileUploadController {
    @Value("${app.upload-path}")
    private String uploadPath;

    /**
     * 客户端文件上传保存至指定目录
     *
     * @param request
     * @param saveDirPrefix 文件保存路劲
     * @return
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadFile(HttpServletRequest request, String saveDirPrefix) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        String fileName = file.getOriginalFilename();
        fileName = new StrongUuidGenerator().getNextId() + fileName.substring(fileName.indexOf("."));
        //保存
        try {
            String filePath = uploadPath + saveDirPrefix;
            File fileDir = new File(filePath);
            if (!fileDir.exists())
                fileDir.mkdirs();
            File targetFile = new File(filePath, fileName);
            targetFile.deleteOnExit();
            file.transferTo(targetFile);
            //返回图片下载地址
            return ResultUtils.success(saveDirPrefix + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.error(ResultCode.APP_ICO_FAILED);
        }

    }
}

使用MultipartHttpServletRequest可以获取文件流和相关参数。

文件上传进度监控

我们可以将文件分成多个块进行分批次传输,主要是在RequestBody的writeTo方法中计算累计发送的文件字节数,具体实现如下:

/**
 * 文件上传进度
 */
@Test
public void fileuploadProgressMonitor() throws InterruptedException {
    RequestBody progressRequestBody = new RequestBody() {
        //一次发送2K数据
        private static final int SEGMENT_SIZE = 2 * 1024;
        private File file = new File("D:\\RequestBody.png");

        private ProgressListener listener = new ProgressListener() {
            @Override
            public void transferred(long size) throws IOException {
                BigDecimal decimalSize = new BigDecimal(size * 100);
                BigDecimal decimalLen = new BigDecimal(contentLength());
                logger.info("完成:{}%", decimalSize.divide(decimalLen, 2, RoundingMode.HALF_DOWN));
            }
        };

        @Override
        public MediaType contentType() {
            return null;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            logger.info("开始上传文件:{},文件大小:{} 字节", file.getCanonicalPath(), this.contentLength());
            Source source = null;
            try {
                //待发送文件转换为Source
                source = Okio.source(file);
                long total = 0;
                long read;
                while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
                    total += read;
                    sink.flush();
                    this.listener.transferred(total);

                }
            } finally {
                Util.closeQuietly(source);
            }

        }

        @Override
        public long contentLength() throws IOException {
            return file.length();
        }
    };
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", "test", progressRequestBody)
            .build();
    Request request = new Request.Builder()
            .url("http://localhost:8888/base-platform/upload/uploadFile")
            .post(requestBody)
            .build();
    OkHttpClient client = new OkHttpClient();
    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 {
            logger.debug(response.toString());
        }
    });
    Thread.currentThread().join(5000);
}

在writeTo方法中我们其实是使用了okio这个库来进行文件读读写操作,后面也会单独介绍这个IO库的使用。在while中每次发送了2K字节数据,然后把累加器的值传递给外部的监听器,然后打印当前进度。

运行结果如下:

11:17:05.883 [OkHttp http://localhost:8888/...] INFO OkHttpTest - 开始上传文件:D:\RequestBody.png,文件大小:6245 字节
11:17:05.897 [OkHttp http://localhost:8888/...] INFO OkHttpTest - 完成:32.79%
11:17:05.898 [OkHttp http://localhost:8888/...] INFO OkHttpTest - 完成:65.59%
11:17:05.901 [OkHttp http://localhost:8888/...] INFO OkHttpTest - 完成:98.38%
11:17:05.901 [OkHttp http://localhost:8888/...] INFO OkHttpTest - 完成:100.00%
11:17:05.948 [OkHttp http://localhost:8888/...] DEBUG OkHttpTest - Response{protocol=http/1.1, code=200, message=, url=http://localhost:8888/base-platform/upload/uploadFile}

the end

至此okhttp3的基础使用都讲完了,看完本篇文章应该对常见的场景都能应付自如了。后面有时间在介绍拦截器等高级主题。

最后附上整个测试代码,注意最后的文件上传后端处理仅供参考。

import com.sun.istack.internal.Nullable;
import okhttp3.*;
import okhttp3.internal.Util;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.TimeUnit;

/**
 * @auther gongxufan
 * @date 2018/7/9
 **/
public class OkHttpTest {

    private static final Logger logger = LoggerFactory.getLogger(OkHttpTest.class);
    private static String url = "https://www.jianshu.com";

    /**
     * 同步GET请求
     * -OkHttpClient#Builder构造客户端对象;
     * -构造Request对象;
     * -通过前两步中的对象构建Call对象;
     * -通过Call#execute(Callback)方法来提交异步请求;
     */
    @Test
    public void syncGetCall() throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求,可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        Response response = call.execute();
        logger.debug(response.body().string());
    }

    /**
     * 异步GET请求
     * -OkHttpClient#Builder构造客户端对象;
     * -构造Request对象;
     * -通过前两步中的对象构建Call对象;
     * -通过Call#enqueue(Callback)方法来提交异步请求;
     */
    @Test
    public void asyncGetCall() throws Exception {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
        ;
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求,可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.error("onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                logger.debug("onResponse: " + response.body().string());
            }
        });
        //等待请求线程,否则主线程结束无法看到请求结果
        Thread.currentThread().join();
    }

    /**
     * post发送String数据
     * 这里使用github的markdown编辑器API,我们发送一个文本,编辑器会返回格式化富文本信息
     */
    @Test
    public void postStringTest() throws InterruptedException {
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        String requestBody = "hello github";
        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(RequestBody.create(mediaType, requestBody))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.debug("onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                logger.debug(response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < headers.size(); i++) {
                    sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
                }
                logger.debug("headers:\n{}", sb.toString());
                logger.debug("onResponse: " + response.body().string());
            }
        });
        Thread.currentThread().join();
    }

    /**
     * 发送字节流
     * 可以使用create方法或者重载RequestBody进行自定义构造
     *
     * @throws InterruptedException
     * @throws UnsupportedEncodingException
     */
    @Test
    public void postBytesTest() throws InterruptedException, UnsupportedEncodingException {
        RequestBody requestBody = new RequestBody() {
            @Nullable
            @Override
            public MediaType contentType() {
                return MediaType.parse("text/x-markdown; charset=utf-8");
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.writeUtf8("你好,github");
            }
        };
        //requestBody = RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), "你好,github".getBytes("utf-8"));
        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(requestBody)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.debug("onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                logger.debug(response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < headers.size(); i++) {
                    sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
                }
                logger.debug("headers:\n{}", sb.toString());
                logger.debug("onResponse: " + response.body().string());
            }
        });
        Thread.currentThread().join();
    }

    /**
     * 发送文件
     *
     * @throws InterruptedException
     */
    @Test
    public void postFileTest() throws InterruptedException {
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        OkHttpClient okHttpClient = new OkHttpClient();
        File file = new File("D:\\code\\work\\egovaCloud\\src\\test\\java\\test.md");
        Request request = new Request.Builder()
                .url("https://api.github.com/markdown/raw")
                .post(RequestBody.create(mediaType, file))
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.debug("onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                logger.debug(response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < headers.size(); i++) {
                    sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
                }
                logger.debug("headers:\n{}", sb.toString());
                logger.debug("onResponse: " + response.body().string());
            }
        });
        Thread.currentThread().join(5000);
    }

    /**
     * post提交表单,使用FormBody来构造表单键值对
     */
    @Test
    public void postFormDataTest() throws InterruptedException {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("search", "java")
                .build();
        Request request = new Request.Builder()
                .url("https://en.wikipedia.org/w/index.php")
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.debug("onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                logger.debug(response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < headers.size(); i++) {
                    sb.append(headers.name(i) + ":" + headers.value(i)).append("\n");
                }
                logger.debug("headers:\n{}", sb.toString());
                logger.debug("onResponse: " + response.body().string());
            }
        });
        Thread.currentThread().join(5000);
    }

    /**
     * 上传文件同时写到额外表单参数
     *
     * @throws Exception
     */
    @Test
    public void postMutilPartFormData() throws Exception {
        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("extra", "extra args")
                .addFormDataPart("file", "logo.png",
                        RequestBody.create(MEDIA_TYPE_PNG, new File("D:\\code\\work\\egovaCloud\\src\\main\\resources\\static\\image\\logo.png")))
                .build();
        Request request = new Request.Builder()
                .url("http://localhost:8888/base-platform/upload/uploadFile")
                .post(requestBody)
                .build();
        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        logger.debug(response.body().string());
    }

    /**
     * 文件上传进度
     */
    @Test
    public void fileuploadProgressMonitor() throws InterruptedException {
        RequestBody progressRequestBody = new RequestBody() {
            //一次发送2K数据
            private static final int SEGMENT_SIZE = 2 * 1024;
            private File file = new File("D:\\RequestBody.png");

            private ProgressListener listener = new ProgressListener() {
                @Override
                public void transferred(long size) throws IOException {
                    BigDecimal decimalSize = new BigDecimal(size * 100);
                    BigDecimal decimalLen = new BigDecimal(contentLength());
                    logger.info("完成:{}%", decimalSize.divide(decimalLen, 2, RoundingMode.HALF_DOWN));
                }
            };

            @Override
            public MediaType contentType() {
                return null;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                logger.info("开始上传文件:{},文件大小:{} 字节", file.getCanonicalPath(), this.contentLength());
                Source source = null;
                try {
                    //待发送文件转换为Source
                    source = Okio.source(file);
                    long total = 0;
                    long read;
                    while ((read = source.read(sink.buffer(), SEGMENT_SIZE)) != -1) {
                        total += read;
                        sink.flush();
                        this.listener.transferred(total);

                    }
                } finally {
                    Util.closeQuietly(source);
                }

            }

            @Override
            public long contentLength() throws IOException {
                return file.length();
            }
        };
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "test", progressRequestBody)
                .build();
        Request request = new Request.Builder()
                .url("http://localhost:8888/base-platform/upload/uploadFile")
                .post(requestBody)
                .build();
        OkHttpClient client = new OkHttpClient();
        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 {
                logger.debug(response.toString());
            }
        });
        Thread.currentThread().join(5000);
    }

    public interface ProgressListener {
        void transferred(long size) throws IOException;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值