Here is the request that i am sending as multipart setting files and plain text params.
suspend fun updateUserProfileInformation(
docList: List<File>,
type: String?,
reason: String?,
address: String?,
requiredOtp: String?
): CommonOtpRes {
val formData = formData {
for (file in docList) {
this.appendInput(
key = "documents",
headers = Headers.build {
append("Content-Type", "image/jpeg")
append(HttpHeaders.ContentLength, file.length())
append(HttpHeaders.ContentDisposition, "filename=${file.name}")
},
size = file.length()
) { buildPacket { writeFully(file.readBytes()) } }
}
append("type", type ?: "")
append("reason", reason ?: "")
if(!address.isNullOrEmpty())
append("address", address)
if(!requiredOtp.isNullOrEmpty())
append("requiredOTPS", requiredOtp)
}
val response: HttpResponse = client.post("$VERSION/user-request/submit") {
setBody(
MultiPartFormDataContent(
formData
)
)
}
return response.body()
}
Now what i need to do is once that gets called and response is received i need to check that whether some specific status code is received then i need to modify the request and resend it with updated parameters cloning the previous request body and adding additional type param to it. I am receiving the request.body type as the StreamRequestBody type now this class is internal and not directly accessible, so need to find a way to modify the content and resend it with new additional params.
Debug request body
What i have tried so far, original is the request from inside the interceptor once the response is received.
if(original.body is RequestBody && original.body?.isOneShot() == true) {
val buffer = Buffer()
original.body?.writeTo(buffer)
val bodyString = buffer.readUtf8()
Timber.e("Body Contents: $bodyString")
}
But here the content received is empty.
Previously with Retrofit this was how i had achieved the same but with ktor that is not possible somehow.
val builder: MultipartBody.Builder = MultipartBody.Builder()
.setType(MultipartBody.FORM)
val requestBody = original.body as MultipartBody
for (part in requestBody.parts) {
if (part.body.contentType() == "application/json; charset=utf-8".toMediaTypeOrNull() && part.headers?.get(
"Content-Disposition"
)?.contains("type") == true
) {
builder.addFormDataPart("type", Gson().toJson(list))
} else {
builder.addPart(part)
}
}
val multipartReq = original.newBuilder()
.method(original.method, builder.build())
.build()
return multipartReq
yashctn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.