Retrofit2 POST 请求,以正文作为参数 Kotlin

问题描述 投票:0回答:2

我是 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
) 
kotlin http-post retrofit2
2个回答
1
投票
@POST("signin")
suspend fun signIn(
    @Body body: User,
): ResponseBody

顺便说一句,仅当您的 API 支持时,您才可以使用正文代替查询参数。 另外,我建议使用 ResultWrapper。 在一个地方使用 Retrofit 和协程处理错误


0
投票
 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())

            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.