5

I want to send a post request in which I've to send some data which includes json formatted data and a image file.

When I'm sending request separately then its working fine, but does'nt wokring together.

Please help me here, how to acheive this.

What I've used for sending json formatted data:

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

Its working fine when I've not used the file. But I've to send a image file as multipart data with this request, then how to do it.

Prithniraj Nicyone
  • 5,021
  • 13
  • 52
  • 78

2 Answers2

1

Kotlin usage

Try using this piece of code. It worked in my case. And let me know if it works and make it the right answer (:

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

I've used this version of okhttp

    implementation 'com.squareup.okhttp3:okhttp:4.3.1'
Mateus Nascimento
  • 815
  • 10
  • 11
-2

Try this to send files:

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();
    }
Nishan Khadka
  • 385
  • 1
  • 2
  • 14