I am learning the use of Retrofit2 to make REST Api calls from Android app. I have an end point which accepts two parts as given below:
@Multipart
@POST("user/personImageUpload5")
suspend fun uploadUImage2(
@Part(value = "person") person: PersonFull,
@Part personImage: MultipartBody.Part
) : BaseResponseModel
The end point works well when I test it with postman.
I have generated the postman code snippet in java and converted it to kotlin and the resulting code is listed below:
var client = OkHttpClient().newBuilder()
.build();
var mediaType = "text/plain".toMediaTypeOrNull();
var body = MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("person", null,
RequestBody.create(
"application/json".toMediaTypeOrNull(),
Gson().toJson(personFull)))
.addFormDataPart("productImage","/C:/Nazir/eclipseprojects/images/15224.jpeg",
RequestBody.create(
"application/octet-stream".toMediaTypeOrNull(),
file))
.build();
var request = Request.Builder()
.url(baseUrl + "user/personImageUpload5")
.method("POST", body)
.addHeader("Authorization", token)
.build();
return response = client.newCall(request).execute();
When I execute, the code works well until the last line where the request is actually executed. There the execution stays forever and nothing happens. No okhttp messages are logged in logcat either. Any suggestions and what could be wrong here.
Following code worked:
@Multipart
@POST("user/personImageUpload4")
suspend fun uploadUImage2(
@Part("person") person: RequestBody,
@Part personImage: MultipartBody.Part
) : BaseResponseModel
Here is how I made the call:
val filesDir = context.filesDir
var tempFile = "imagetrf.jpg"
val file = File(filesDir, imageUrlPath)
val inputStream = context.contentResolver.openInputStream(imageUri)
val outputStream = FileOutputStream(file)
inputStream!!.copyTo(outputStream)
val requestBodyFile = file.asRequestBody("image/*".toMediaTypeOrNull())
val part1 = MultipartBody.Part.createFormData("personImage",imageUrlPath, requestBodyFile)
val returnPerson: RequestBody = RequestBody.create("application/json".toMediaTypeOrNull(), Gson().toJson(
PersonModel(personFull)
))
var baseResponseModel = savePhotoAPI.uploadUImage2(returnPerson,part1)