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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With