添加进请求体
File file =File_change.compressImage(bitmap);//bitmap是图片资源
MediaType mediaType = MediaType.parse("application/octet-stream");//设置类型,类型为八位字节流
OkHttpClient client = new OkHttpClient();
//POST请求
RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体
MultipartBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image_file", file.getName(), requestBody)//文件名,请求体里的文件
.build();
Request request = new Request.Builder()
.url("接口")
//默认就是GET请求就可以不写,这里是post
.post(multipartBody)
.build();
图片上传的时候记得压缩哈
call.enqueue(new okhttp3.Callback() {//todo 图片太大会报错 expected 346 bytes but received 8192
@Override
public void onFailure(Call call, final IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
e.printStackTrace();
//失败的操作
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//成功的操作
}
});
我常用的质量压缩,大家可以参考一下
**
* 质量压缩方法
* @param image
* @return
*/
public static Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 90;
while (baos.toByteArray().length / 1024 > 500) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset(); // 重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
options -= 10;// 每次都减少10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
return bitmap;
}
以上是所有内容,记录一下!