Android,okhttp同时上传文件和json

时间:2016-03-19 01:08:33

标签: android okhttp okhttp3

我okhttp3,我希望能够上传文件,上传JSON数据,但发现只能同时上传HashMap,请问,如何上传JSON?我发现RequestBody类方法创建,上传json和上传文件的方法是重载

1 个答案:

答案 0 :(得分:0)

复杂请求----- Multipart / form-data

找一些示例代码,但我仍然不明白:

MultipartBody.Builder builder = new MultipartBody.Builder();
        MultipartBody body = builder
                .setType(MultipartBody.FORM)
                .addPart(
                        Headers.of("Content-Disposition", "form-data; name=\"title\""),
                        RequestBody.create(null, "Square Logo"))
                .addPart(
                        Headers.of("Content-Disposition", "form-data; name=\"image\""),
                        RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
                .build();

        Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
                .url("https://api.imgur.com/3/image")
                .post(body)
                .build();

        Response response = OkHttpUtils.getInstance().getOkHttpClient().newCall(request).execute();