我正在開發一個與 API 介面以從 MySQL 資料庫中進行選擇和更新的應用程式。
我正在使用帶有 Retrofit 和 Moshi 轉換器的 Kotlin。(由于我是新手,所以這個應用程式是從https://developer.android.com/courses/pathways/android-basics-kotlin-unit-4-pathway-2上的 Mars Photo 代碼修改而來的。)
由于從上面的教程中構建,我已經成功地在 Retrofit 中實作了 GET 部分,但是我在 POST 到資料庫中花費了很多時間。
通過 API 更新的 POST 在 Postman 中作業,但我嘗試了多種方法在我的應用程式中復制它但沒有成功。我嘗試了一個非常基本的 POST 傳遞我的資料物件(作為標準 Kotlin vars 以及帶注釋的 Json 或帶注釋的 SerializedName),并且我嘗試了帶欄位的 Formurlencoded 和帶部件的 Multipart。
我包括我希望的所有相關代碼(至少是最新的嘗試)。感謝您的幫助!
*** My Data Class (have also tried it without the Json annoations) ***
import com.squareup.moshi.Json
data class IsVotes(
@Json(name = "is_votes") var isVotes: String,
@Json(name = "is_id") var isId: String
)
------
*** The function in the ViewModel file - called by a Databinded button click and using static vars for testing
fun updateIsVotes(){
viewModelScope.launch {
// TODO: Response success var?
try {
IsApi.retrofitService.updateVotesAsync( IsVotes("99","5"))
_putStatus.value = IsPutStatus.SUCCESS
}
catch (e:Exception) {
_putStatus.value = IsPutStatus.ALMOST
}
}
}
--------
*** The api service file and call ****
package com.viscidcreates.iswhatapi.network
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import kotlinx.coroutines.Deferred
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.*
private const val BASE_URL = "https://beamcreates.com/is_things_api/v1/"
const val getThings = "Api.php?apicall=getthings"
const val updateVotes = "Api.php?apicall=updatevotes"
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BASE_URL)
.build()
interface IsApiService {
@GET(getthings)
suspend fun getThings(): List<IsThing>
@POST(updateVotes)
suspend fun updateVotesAsync(@Body votes: IsVotes): Deferred<Response<Void>>
}
object IsApi {
val retrofitService: IsApiService by lazy {
retrofit.create(IsApiService::class.java)
}
}
uj5u.com熱心網友回復:
通常,您將@Body類創建為:
@JsonClass(generateAdapter = true)
data class IsVotes(
@Json(name = "is_votes")
val isVotes: String,
@Json(name = "is_id")
val isId: String
)
要添加 MoshiGenerator,您需要添加build.gradle
kapt "com.squareup.moshi:moshi-kotlin-codegen:1.13.0"
但首先你應該嘗試是否是縮小/混淆的問題,并
更改@Json(name="is_votes")為.@field:Json(name="is_votes")is_id
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/449125.html
