简体   繁体   中英

How Do I Send My Multipart Form Data POST Request In Kotlin Using Retrofit and OkHttp?

I am trying to send multipart form data to a server: https://example.com/mail/

The data is a pdf file and a json object. I have to the best of my ability followed various examples but am not having any luck. It starts with a call in onCreate of my Activity to uploadToServer(context) and ends up crashing in enqueue.

class APIClient {
private var retrofit: Retrofit? = null

fun getClient(): Retrofit? {
    val interceptor = HttpLoggingInterceptor()
    interceptor.level = HttpLoggingInterceptor.Level.BODY
    val client = OkHttpClient.Builder().addInterceptor(interceptor).build()
    retrofit = Retrofit.Builder()
        .baseUrl("https://example.com/mail/")
        //.addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build()
    return retrofit
}

interface UploadAPIs {
    @Multipart
    @POST("https://example.com/mail/")
    fun uploadImage(
        @Part("report") file: MultipartBody.Part,
        @Part("json") requestBody: RequestBody
    ): Call<String>
}

fun makeGSONRequestBody(jsonObject: Any): RequestBody {
    return Gson().toJson(jsonObject).toRequestBody("multipart/form-data".toMediaTypeOrNull())

fun uploadToServer(context: Context) {
    //Create a file object using file path
    var file = File(context.getExternalFilesDir(null), "/Hello.pdf")

    var details: MutableMap<String, String> = mutableMapOf()
    details["clockinTime"] = "2100"
    details["location"] = "Smith St"
    details["companyEmail"] = "example@gmail.com"
    Log.d("TRACE", "Check the JSON string" + Gson().toJson(details))

    var reqBod = makeGSONRequestBody(details)
    val inputStream = context.contentResolver.openInputStream(Uri.fromFile(file))
    val requestFile =
    inputStream!!.readBytes().toRequestBody("multipart/form-data".toMediaType())
    var fileBody =  MultipartBody.Part.createFormData("image", file.name, requestFile)
    val apiInterface = APIClient().getClient()?.create<UploadAPIs>(UploadAPIs::class.java)

    val call: Call<String> = apiInterface!!.uploadImage(fileBody, reqBod)
    call.enqueue(object : Callback<String> {
        override fun onResponse(call: Call<String>, response: Response<String>) {
            Log.d("TRACE", "response is$response")
        }

        override fun onFailure(call: Call<String>, t: Throwable) {
            Log.d("TRACE", "didn't work$t")
        }
})

Any help would be so greatly appreciated.

EDIT I changed the requestFile variable to mime type "image/*". Now I am getting the error:

2022-01-06 00:37:08.449 540-587/system_process D/ArtManagerInternalImpl: /data/misc/iorapd/com.reportsapp/1/com.reportsapp.MainActivity/compiled_traces/compiled_trace.pb doesn't exist

It may be caused by your wrong media type, you can try it.You can post the error message

val requestFile = RequestBody.create(MediaType.parse("image/*"), file)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM