Skip to content

Instantly share code, notes, and snippets.

@EhsanSetayesh
Created January 30, 2024 11:10
Show Gist options
  • Save EhsanSetayesh/f128eae76adc0f0420b9d2eec95fe1f5 to your computer and use it in GitHub Desktop.
Save EhsanSetayesh/f128eae76adc0f0420b9d2eec95fe1f5 to your computer and use it in GitHub Desktop.
Create retrofit Multi Part api call to upload cert file
@POST("api/v1/testApp/sign")
@Multipart
suspend fun sign(
@Part certFile: MultipartBody.Part,
@Part passwordFile: MultipartBody.Part,
@Part("data") data: RequestBody
): Response<CustomResponseModel>
private fun readPfxFileFromAssets(context: Context, fileName: String): ByteArray {
val inputStream: InputStream = context.assets.open(fileName)
val buffer = ByteArrayOutputStream()
val bufferSize = 1024
val bufferData = ByteArray(bufferSize)
var bytesRead: Int
while (inputStream.read(bufferData, 0, bufferSize).also { bytesRead = it } != -1) {
buffer.write(bufferData, 0, bytesRead)
}
return buffer.toByteArray()
}
private fun createPfxFilePart(context: Context, fileName: String): MultipartBody.Part {
val pfxFileData = readPfxFileFromAssets(context, fileName)
// val base64 = Base64.encodeToString(pfxFileData, Base64.NO_WRAP)
val requestBody = RequestBody.create("application/x-pkcs12".toMediaTypeOrNull(), pfxFileData)
return createFormData("CertFile", fileName, requestBody)
}
private const val MULTIPART_FILE_CONTENT_TYPE = "application/x-pkcs12"
private const val MULTIPART_DATA_CONTENT_TYPE = "application/json"
private const val CERT_FILE_NAME = "myCert.pfx"
val requestBody = RequestBody.create(
MULTIPART_FILE_CONTENT_TYPE.toMediaTypeOrNull(),
Base64.decode(CERT_BASE64, Base64.NO_WRAP)
)
val pfxFilePart = createFormData("CertFile", CERT_FILE_NAME, requestBody)
val dataRequestBody: RequestBody =
jsonString.toRequestBody(MULTIPART_DATA_CONTENT_TYPE.toMediaTypeOrNull())
val generalResponseModel = service.sign(
certFile = pfxFilePart,
passwordFile = createFormData("PasswordFile", MULTIPART_FILE_PASSWORD),
data = dataRequestBody
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment