android - 如何使用 Retrofit 将参数传递给 POST 请求,然后序列化请求?
问题描述
我正在从iOS切换到Android并尝试使用Retrofit实现 POST 请求,但不明白我的错误,请检查我的代码,并告诉我哪里出错了。
通过Postman一切正常,身体原始值:{"players": ["player"], "action" : "add"}
我的代码下面没有数据类。
界面
interface ApiRequests {
@POST("/startup")
fun getDataVenom(
@Field("players") players: Array<String>,
@Field("action") action: String
): Call<ObjectFromResponse>
}
获取数据:
private fun getCurrentData() {
tv_textView.visibility = View.GONE
tv_timeStamp.visibility = View.GONE
progressBar.visibility = View.VISIBLE
val api2 = Retrofit.Builder()
.baseUrl(BASE_URL_VENOM)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiRequests::class.java)
val players: Array<String> = arrayOf("players")
GlobalScope.launch(Dispatchers.IO) {
try {
val response = api2.getDataVenom(players = players, action = "add").awaitResponse()
if (response.isSuccessful) {
val data = response.body()!!
Log.d(TAG, data.toString())
withContext(Dispatchers.Main) {
tv_textView.visibility = View.VISIBLE
tv_timeStamp.visibility = View.VISIBLE
progressBar.visibility = View.GONE
}
}
} catch (e: Exception) {
withContext(Dispatchers.Main){
Toast.makeText(
applicationContext,
"Seems like something went wrong...",
Toast.LENGTH_SHORT
).show()
}
}
}
}
解决方案
您应该使用@Body
注释:
当您想直接控制 POST/PUT 请求的请求体时,在服务方法参数上使用此注解...对象将使用 Retrofit 实例 Converter 进行序列化,结果将直接设置为请求体。正文参数不能为空。
你可能会使用
@POST("/startup")
fun getDataVenom(
@Body body: BodyDTO
): Call<ObjectFromResponse>
BodyDTO
在哪里
data class BodyDTO(
@SerializedName("players") private val players: Array<String>,
@SerializedName("action") private val action: String
)
推荐阅读
- reactjs - onSubmit 对多个项目做出反应
- yaml - Python:从 .yaml 读取信息
- c# - C# 参数 1:无法从 'string' 转换为 'char'
- ruby-on-rails - 计算rails postgresql查询中的时间差
- python - Django:使用模板中的元素动态设置 url
- java - 一个线程池 VS。java spring boot(web)项目中的许多线程池
- java - 一天前消费rest angular 6和Java Spring的日期
- c# - IOException:Visual Studio 中的“找不到资源”
- php - 为什么 laravel 的门面表现得像一个单例?
- python - CPLEX 错误 1016:促销版,使用学术版 CPLEX