【发布时间】:2021-09-24 00:45:25
【问题描述】:
我的代码有问题,我想发送带有 x-www-form-urlencoded 或 form-data 的帖子,我需要发送两个参数:
- 电子邮件:字符串
- 密码:字符串
我在Json中收到两个参数后:
- 令牌:字符串
- 成功:布尔值
在表单数据中发送电子邮件和密码很重要。
邮递员示例:
【问题讨论】:
标签: android json postman retrofit form-data
我的代码有问题,我想发送带有 x-www-form-urlencoded 或 form-data 的帖子,我需要发送两个参数:
我在Json中收到两个参数后:
在表单数据中发送电子邮件和密码很重要。
邮递员示例:
【问题讨论】:
标签: android json postman retrofit form-data
按照以下步骤使用 Retrofit 在 android 中发送表单数据或 URL 编码数据。
构建.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'
}
制作接口类名
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_URL 将是 https://URLEJEMPLO.com
【讨论】: