okhttp3上传图片

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))

你可能感兴趣的:(android)