上传图片时一般提交图片文件,okhttp3的RequestBody类有对应的创建文件body的工厂方法
RequestBody.create(MediaType.parse("image/jpeg"), file)
在某些场景,比如编辑图片、裁剪头像等,编辑后的bitmap只在提交时使用一次,可以直接将bitmap写入到okhttp的输出流中
参考Okhttp提供的文件类型的body
public static RequestBody create(final @Nullable MediaType contentType, final File file) {
if (file == null) throw new NullPointerException("content == null");
return new RequestBody() {
@Override public @Nullable MediaType contentType() {
return contentType;
}
@Override public long contentLength() {
return file.length();
}
@Override public void writeTo(BufferedSink sink) throws IOException {
Source source = null;
try {
source = Okio.source(file);
sink.writeAll(so