简体   繁体   English

如何使用 Retrofit 和 OkHttp 在 Kotlin 中发送我的多部分表单数据 POST 请求?

[英]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/我正在尝试将多部分表单数据发送到服务器: https://example.com/mail/

The data is a pdf file and a json object.数据是 pdf 文件和 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.它首先在我的 Activity 的 onCreate 中调用 uploadToServer(context) 并最终在入队中崩溃。

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/*".编辑我将 requestFile 变量更改为 mime 类型“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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法为我的Android应用程序使用Java中的okHTTP multipart-form数据重新创建cURL POST请求 - Not able to recreate a cURL POST request using okHTTP multipart-form data in Java for my android app 使用带有行 json 数据 kotlin 的 Retrofit2 发送发布请求 - send post request using Retrofit2 with row json data kotlin 如何使用改造在多部分表单请求中发送POJO对象? - How can I send a POJO object in a Multipart-form Request using Retrofit? 如何使用Retrofit发送multipart / form-data? - How to send multipart/form-data with Retrofit? 如何使用 Fuel for Kotlin POST 多部分/表单数据? - How to POST multipart/form-data using Fuel for Kotlin? 使用翻新的多部分POST请求 - Multipart POST request using Retrofit 我在应用程序中使用此功能,使用multipart / form-data中的OkHttp3将图像发布到服务器 - I'm using this function in an app to post an image to the server using OkHttp3 in multipart/form-data 在Retrofit中,如何以原始形式发送发布请求和数据? - How to send post request along with data in raw form in Retrofit? 使用 Retrofit kotlin 发布表单数据参数 - Post form data params using Retrofit kotlin 使用多部分表单数据无法到达服务器来改进POST请求 - Retrofit POST request with multipart form data not reaching server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM