如何使用 FORM-DATA 或 x-www-form-urlencoded 和 Android 来执行 post 请求?

How to do a post request using FORM-DATA or x-www-form-urlencoded with Android?

我的代码有问题,我想用 x-www-form-urlencoded 或 form-data 发送 post,我需要发送两个参数:

在 Json 中收到两个参数后:

请务必在 Form-Data 中发送电子邮件和密码。

邮递员示例:

按照以下步骤使用 Retrofit 在 android 中发送表单数据或 URL 编码数据。

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'
}

制作界面class名称

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

而你Constants.BASE_URLhttps://URLEJEMPLO.com