0

I have an issue with my code, I want to send a post with x-www-form-urlencoded or form-data, I need to send two parameters:

  • Email: String
  • Password: String

And after I receive two parameters in Json:

  • Token: String
  • Success: Boolean

It's important that the Email and Password are sent in Form-Data.

Postman example:

Postman example

1 Answer 1

1

Follow these steps to send Form data or URL encoded data in android using Retrofit.

Build.gradle

//Retrofit
implementation "com.squareup.okhttp3:okhttp:3.8.0"
implementation "com.squareup.okhttp3:logging-interceptor:3.8.0"
implementation ("com.squareup.retrofit2:retrofit:2.5.0"){
// exclude Retrofit’s OkHttp peer-dependency module and define your own module 
import
exclude module: 'okhttp'
}

Make interface class name

ApiInterface.kt

import retrofit2.Call
import retrofit2.http.*
interface ApiInterface {

@FormUrlEncoded
@POST("")
fun register(
    @Field("email") email: String,
    @Field("password") password: String?,
): Call<EmailResponse>
}

MainActivity.kt

val retrofit = Retrofit.Builder()
    .baseUrl(Constants.BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build()
val service = retrofit.create(ApiInterface::class.java)
val call = service.register(email, password)


call!!.enqueue(object : Callback<EmailResponse> {
    override fun onResponse(
        call: Call<EmailResponse>,
        response: Response<EmailResponse>,
    ) {
        if (response.isSuccessful) {

            val emailResponse: EmailResponse = response.body()!!
            val token = emailResponse.token
            val success = emailResponse.success

        }
    }

    override fun onFailure(call: Call<EmailResponse>, t: Throwable) {
        Log.e(TAG, "onFailure: ")
    }
})

EmailResponse.kt

data class EmailResponse(
val token: String,
val success: Boolean,
)

And you Constants.BASE_URL will be https://URLEJEMPLO.com

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.