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

时间:2018-04-06 04:51:26

标签: android okhttp3 square okhttp

我想发送一个帖子请求,我发送一些包含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();

当我没有使用该文件时,它正常工作。 但是,我已经将此图像文件作为多部分数据发送给该请求,然后如何进行。

2 个答案:

答案 0 :(得分:1)

科特琳的用法

尝试使用这段代码。以我为例。让我知道它是否有效,并做出正确的答案(:

    private const val CONNECT_TIMEOUT = 15L
    private const val READ_TIMEOUT = 15L
    private const val WRITE_TIMEOUT = 15L

    private fun performPostRequest(urlString: String, jsonString: String, image: File, token: String): String? {
        /* https://github.com/square/okhttp#requirements
        OkHttp uses your platform's built-in TLS implementation.
        On Java platforms OkHttp also supports Conscrypt,
        which integrates BoringSSL with Java.
        OkHttp will use Conscrypt if it is the first security provider: */
        Security.insertProviderAt(Conscrypt.newProvider(), 1)

        return try {
            val client = OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .build()

            val body: RequestBody = MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("parameterNameInServerSideJSON", jsonString)
                .addFormDataPart("parameterNameInServerSideImage", "test.jpeg", image.asRequestBody("image/jpg".toMediaTypeOrNull()))
                .build()

            val request = Request.Builder()
                .url(URL(urlString))
                .header("Authorization", token) // in case you use authorization
                .post(body)
                .build()

            val response = client.newCall(request).execute()
            response.body?.string()
        }
        catch (e: IOException) {
            e.printStackTrace()
            null
        }
    }

我用过这个版本的okhttp

    implementation 'com.squareup.okhttp3:okhttp:4.3.1'

答案 1 :(得分:-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();
    }
相关问题