使用Retrofit 2上传图像/pdf文件和其他文本数据到服务器

问题描述 投票:0回答:1

我只是从服务器收到状态代码 500 的错误,而不是响应。尝试了很多方法都无法找出错误

依赖关系

    implementation ("com.squareup.retrofit2:retrofit:2.9.0")
    implementation ("com.squareup.retrofit2:converter-gson:2.9.0")
    implementation ("com.squareup.okhttp3:okhttp:4.9.1")

这是我用于向服务器发送请求的 Api 接口

@Multipart
    @POST("/api/v1/itf/itr-filling")
    fun itrFiling(

        @Part("itrSelectFile") itrSelectFile: RequestBody,
        @Part("selectWord") selectWord: RequestBody,
        @Part("panId") panId: RequestBody,
        @Part("password") password: RequestBody,
        @Part("email") email: RequestBody,
        @Part("mobileNumber") mobileNumber: RequestBody,
        @Part form16Gov: MultipartBody.Part,
        @Part bankAccount: MultipartBody.Part,
        @Part aadharCard: MultipartBody.Part
    ): Call<ItrFilingResponse>

这是我的改造实例

object RetrofitInstance {

    val api:ABTaxAPI by lazy {
        Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ABTaxAPI::class.java)
    }
}
**global variable**

私有变量 mAadharPart:MultipartBody.Part?=null


**this is the api call with dummy data**

binding?.btnSubmitItrFilingDetails?.setOnClickListener {
            val selectFile = "ITR-12"

            val selectWord = "sk"
            val panId = "DTTPA2626L"
            val password = "1wq20op9"
            val email = "[email protected]"
            val mobile = "125495801"


            val selecFileBody = selectFile.toRequestBody("multipart/form-data".toMediaTypeOrNull())
            val selectWordBody = selectWord.toRequestBody("multipart/form-data".toMediaTypeOrNull())
            val panIdBody = panId.toRequestBody("multipart/form-data".toMediaTypeOrNull())
            val passwordBody = password.toRequestBody("multipart/form-data".toMediaTypeOrNull())
            val emailBody = email.toRequestBody("multipart/form-data".toMediaTypeOrNull())
            val mobileBody = mobile.toRequestBody("multipart/form-data".toMediaTypeOrNull())

            val sharedPreferences =
                getSharedPreferences(Constants.TOKEN_PREFERENCES, Context.MODE_PRIVATE)
            val authToken = sharedPreferences.getString(Constants.AUTH_TOKEN, "")

            Toast.makeText(this@ITRFiling,authToken,Toast.LENGTH_SHORT).show()

            showProgressDialog("Please wait")
//        Toast.makeText(this@HomeActivity,authToken,Toast.LENGTH_SHORT).show()
            val call: Call<ItrFilingResponse> = RetrofitInstance.api.itrFiling(selecFileBody,selectWordBody,panIdBody,passwordBody,emailBody,mobileBody,mForm16Part!!,mBankAccountPart!!,mAadharPart!!)
            call.enqueue(object : Callback<ItrFilingResponse> {
                override fun onResponse(call: Call<ItrFilingResponse>, response: Response<ItrFilingResponse>) {
                    if (response.isSuccessful) {
                        hideProgressDialogue()
                        Log.e("itrFillingResponse",response.body().toString())

                    } else {
                        hideProgressDialogue()
                        // Handle non-successful response (e.g., HTTP error)
                        Log.e("itrFillingResponse",response.code().toString())
                    }
                }

                override fun onFailure(call: Call<ItrFilingResponse>, t: Throwable) {
                    hideProgressDialogue()
                    // Handle failure (e.g., network issues)
                    Toast.makeText(this@ITRFiling, "Request failed: ${t.message}", Toast.LENGTH_SHORT).show()
                }
            })
        }

**选择文件(仅显示aadhar文件的代码选择): **

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode==Activity.RESULT_OK){
            if (requestCode==Constants.SELECT_AADHAR_REQUEST_CODE && data!!.data!=null){
                data.data?.let { uri ->
                    binding?.selectedAadharFile?.text=uri.path
                    binding?.deleteSelectedAadharFile?.visibility=View.VISIBLE

                    val filesDir = applicationContext.filesDir
                    val file = File(filesDir,  "image.${Constants.getFileExtension(this,uri)}")
                    val inputStream = contentResolver.openInputStream(uri)
                    val outputStream = FileOutputStream(file)
                    inputStream!!.copyTo(outputStream)
                    val requestBody = file.asRequestBody("*/*".toMediaTypeOrNull())
                    val part = MultipartBody.Part.createFormData("aadharCard", file.name, requestBody)

                    mAadharPart=part



                }

            }

我期待类似的回复

`包 dev.panwar.abtax.models

数据类 ItrFilingResponse( val __v:整数, val _id:字符串, val aadharCard:字符串, val 银行账户:字符串, val 创建于:字符串, val 电子邮件:字符串, val form16Gov:字符串, val itrSelectFile: 字符串, val 手机号码:字符串, val panId:字符串, val 密码:字符串, val updateAt:字符串 )`

android kotlin retrofit retrofit2 multipartform-data
1个回答
0
投票

响应码500表示服务器端错误

© www.soinside.com 2019 - 2024. All rights reserved.