Uploading Image/pdf files and other text data to server using Retrofit 2

39 Views Asked by At

I am just getting error with status code 500 from server and not the response. Tried many ways but couldn't figure out the mistake

dependencies

    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")

This is my Api Interface for sending request to Server

@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>

This is my retrofit Instance

object RetrofitInstance {

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

global variable

private var 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()
                }
            })
        }

Selecting File(showing code selecting of aadhar file only):

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



                }

            }

I am expecting a response like

package dev.panwar.abtax.models

data class ItrFilingResponse(
    val __v: Int,
    val _id: String,
    val aadharCard: String,
    val bankAccount: String,
    val createdAt: String,
    val email: String,
    val form16Gov: String,
    val itrSelectFile: String,
    val mobileNumber: String,
    val panId: String,
    val password: String,
    val updatedAt: String
)
0

There are 0 best solutions below