我是Kotlin的新手,很难将现有的POST请求参数改为body。我看了其他的答案,但他们都没有类似的代码作为我的请求部分。我不知道如何改变它,只是有很多语法错误。谢谢!
import retrofit2.Call
import retrofit2.http.*
interface PostInterface {
@POST("signin")
fun signIn(@Query("email") email: String, @Query("password") password: String): Call<String>
}
class BasicRepo @Inject constructor(val postInterface: PostInterface) {
fun signIn(email: String, password: String): MutableLiveData<Resource> {
val status: MutableLiveData<Resource> = MutableLiveData()
status.value = Resource.loading(null)
postInterface.signIn(email, password).enqueue(object : Callback<String> {
override fun onResponse(call: Call<String>, response: Response<String>) {
if (response.code() == 200 || response.code() == 201) {
// do something
} else {
// do something
}
}
}
}
}
class User constructor(
email: String,
password: String
)
@POST("signin")
suspend fun signIn(
@Body body: User,
): ResponseBody
顺便说一句,只有在你的API支持的情况下,你才能使用body而不是query参数。另外,我建议使用ResultWrapper。在一个地方用Retrofit和Coroutines处理错误
1. First, in the APIService.kt file add the following @POST annotation:
interface APIService {
// ...
@POST("/api/v1/create")
suspend fun createEmployee(@Body requestBody: RequestBody): Response<ResponseBody>
// ...
}
2. the POST request will look like this:
private fun callLogIn(type: String, email: String, password: String){
// Create Retrofit
val retrofit = Retrofit.Builder()
.baseUrl(CONST.BASE_URL)
.build()
// Create Service
val service = retrofit.create(APIService::class.java)
// Create JSON using JSONObject
val jsonObject = JSONObject()
jsonObject.put("login_id", email)
jsonObject.put("password", password)
// Convert JSONObject to String
val jsonObjectString = jsonObject.toString()
val requestBody = jsonObjectString.toRequestBody("application/json".toMediaTypeOrNull())
CoroutineScope(Dispatchers.IO).launch {
// Do the POST request and get response
val response = service.createEmployee(requestBody)
withContext(Dispatchers.Main) {
if (response.isSuccessful) {
// Convert raw JSON to pretty JSON using GSON library
val gson = GsonBuilder().setPrettyPrinting().create()
val prettyJson = gson.toJson(
JsonParser.parseString(
response.body()
?.string()
)
)
Log.d(" JSON :", prettyJson)
} else {
Log.e("mytag", response.code().toString())
}
}
}
}