okhttp3上传图片

本文详细介绍了使用OkHttp进行文件上传的步骤,包括MediaType设置、RequestBody创建、MultipartBody构建等关键环节,并列举了常见的MediaType类型。

1.okhttp上传文件步骤

public class ImageUpload{

	//1.创建对应的MediaType
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private final OkHttpClient client = new OkHttpClient();

    public void uploadImage(String userName,File file) throws NetworkException{

		//2.创建RequestBody
        RequestBody fileBody = RequestBody.create(MEDIA_TYPE_PNG, file);

		//3.构建MultipartBody
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "testImage.png", fileBody)
                .addFormDataPart("userName", userName)
                .build();

		//4.构建请求
        Request request = new Request.Builder()
                .url("http://xxxxx")
                .post(requestBody)
                .build();

		//5.发送请求
        Response response = client.newCall(request).execute();
    }
}

2.常用MediaType类型

json : application/json
xml : application/xml
png : image/png
jpg : image/jpeg
gif : imge/gif

3.addFormDataPart是对addPart封装:

addPart( 
Headers.of(“Content-Disposition”, “form-data; name=\”file\”;filename=\“testImage.png\""), 
RequestBody.create(MEDIA_TYPE_PNG, fileBody))

addPart(
Headers.of(“Content-Disposition”, “form-data; name=\”userName\”“), 
RequestBody.create(null, userName))
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值