如何使用 json multipart body 和图像文件发送 OkHttp post 请求

Pri*_*one 5 android square okhttp okhttp3

我想发送一个 post 请求,我必须在其中发送一些数据,其中包括 json 格式的数据和一个图像文件。

当我单独发送请求时,它工作正常,但不能一起工作。

请在这里帮助我,如何实现这一点。

我用于发送 json 格式的数据:

Map<String, String> map = new HashMap<>();
postParam.put("title", "XYZ");
postParam.put("isGroup", "true");
postParam.put("ownerId", "123");
JSONArray jsonArray = new JSONArray();
jsonArray.put("1");
jsonArray.put("2");
jsonArray.put("2");
postParam.put("groupMembers", jsonArray.toString());
MediaType JSON = MediaType.parse("application/json");
JSONObject parameter = new JSONObject(postParam);
RequestBody body = RequestBody.create(JSON, parameter.toString());
Request request = new Request.Builder()
            .url(postUrl)
            .addHeader("content-type", "application/json; charset=utf-8")
            .post(body)
            .build();
Run Code Online (Sandbox Code Playgroud)

当我没有使用该文件时,它工作正常。但是我必须使用此请求将图像文件作为多部分数据发送,然后怎么做。

小智 -2

尝试使用此方法发送文件:

public void addFilePart(String fieldName, File uploadFile)
            throws IOException {
        String fileName = uploadFile.getName();
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append(
                "Content-Disposition: form-data; name=\"" + fieldName
                        + "\"; filename=\"" + fileName + "\"")
                .append(LINE_FEED);
        writer.append(
                "Content-Type: "
                        + URLConnection.guessContentTypeFromName(fileName))
                .append(LINE_FEED);
        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        writer.append(LINE_FEED);
        writer.flush();

        FileInputStream inputStream = new FileInputStream(uploadFile);
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        inputStream.close();

        writer.append(LINE_FEED);
        writer.flush();
    }
Run Code Online (Sandbox Code Playgroud)