在很长一段时间里,我一直使用HttpClient这个库进行网络请求的处理。这个库的版本经历了至关大的历史变迁,并且每每存在诸多的BUG。php
咱们一块儿来回顾下HttpClient的的历史,HttpClient项目开始于2001年,它是做为 Jakarta Commons的一个子项目。虽然该项目在2005年被HttpComponents项目所取代,也就是开始了HttpClient 3.x时代。在2007年的时候HttpComponents成为了Apache的顶级项目。并且该项目分裂成两个模块:HttpClient 和 HttpCore 。因此项目的维护者也是看到该库的一些不足因此在不停的更替版本。这样就致使一个问题,各类项目的版本混乱,并且其API也是不兼容,甚至存在使用可能会存在内存泄露的重大BUG版本。html
相信经过本系列文章,你也许会在新的项目中尝试使用现代化的设计更为简洁的okhttp3进行网络相关的开发。java
首先贴上项目地址:square.github.io/okhttp/,若是对源码感兴趣能够fork一份进行学习。该项目star有27k+,确实算是很多。主要仍是其对android的高可用性和socket复用,很是适合移动端的开发,可是对于web端的Java应用开发也是一样的强大。android
其主要特性以下:git
其核心主要有路由、链接协议、拦截器、代理、安全性认证、链接池以及网络适配,拦截器主要是指添加,移除或者转换请求或者回应的头部信息,总流程图以下:github
注:图片来自网络,侵权即删web
这个流程主要是经过Diapatcher不断从RequestQueue中取出请求(Call),根据是否已缓存从内存缓存或是服务器取得请求的数据,其具体实现细节之后再单独撰文讨论。spring
若是你的项目还在使用Java1.6的话赶忙升级JDK吧。apache
okhttp3支持同步和异步请求,若是不想堵塞调用线程咱们通常使用异步请求,在Callback中获取请求返回结果再进一步处理。后端
请求操做通常都有一个套路:
构造OkHttpClient(能够经过new或者Builder)->构造Request->newCall->Call#execute或者Call#enqueue。最后一步操做就是同步或者异步请求的区别。
同步请求的实例代码以下:
/** * 同步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和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}
复制代码
至此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;
}
}
复制代码