【发布时间】:2022-01-06 06:21:07
【问题描述】:
我正在尝试将多部分表单数据发送到服务器:https://example.com/mail/
数据是一个pdf文件和一个json对象。我必须尽我所能遵循各种示例,但没有任何运气。它从我的 Activity 的 onCreate 调用到 uploadToServer(context) 开始,最终在 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")
}
})
任何帮助将不胜感激。
编辑 我将 requestFile 变量更改为 mime 类型“image/*”。现在我收到错误:
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
【问题讨论】:
标签: android kotlin retrofit okhttp