okhttp上传图片实列

只上传是数据时,可使用formbody.builder,上传图片及其他文件时使用MultipartBody.builder;


file=new File(path);  //文件类型

MultipartBody.Builder builder = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("img", file.getName(),
                RequestBody.create(MediaType.parse("image/jpg"), file))
        .addFormDataPart("operation","setUser")
        .addFormDataPart("touxiang",file.getName());

RequestBody requestBody = builder.build();
Request request = new Request.Builder()
        .url("http://nightrain.xyz/Petweb/userServlet")
        //.post(RequestBody.create(mediaType,formBody.toString()))
        .post(requestBody)
        .build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
       
    }
});

你可能感兴趣的:(Android)