Answer the question
In order to leave comments, you need to log in
Retrofit, I don’t understand what should happen when I post, am I doing it right?
As I understand it, the POST annotation marks the method that should send data to the site, so I can’t understand, is something sent to me in the getUserItemPost () method or nothing happens and is it just displayed in the logs?
//интерфейс
@GET("/posts")
fun getCompany(): Call<MutableList<UserItem>>
@POST("posts")
fun getPost(@Body useritem:UserItem):Call<UserItem>
//pojo
data class UserItem(
val body: String,
val id: Int,
val title: String,
val userId: Int
)
//объект
object MyService {
val createConnect = getConnect().create(IApi::class.java)
fun getConnect(): Retrofit {
val retrofit by lazy {
Retrofit
.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return retrofit
}
}
//получение данных со страницы и вывод в логи
fun doGetRetrofit(){
CoroutineScope(Dispatchers.IO).launch {
val company = mIApi.getCompany()
company.enqueue(object : Callback<MutableList<UserItem>> {
override fun onFailure(call: Call<MutableList<UserItem>>, t: Throwable) {}
override fun onResponse(
call: Call<MutableList<UserItem>>,
response: Response<MutableList<UserItem>>
) {
response.body()?.forEach {
Log.e("Company: ", it.id.toString())
}
}
})
}
}
//пытаюсь отправить данные и вывести их в логи
fun getUserItemPost(){
val post = mIApi.getPost(UserItem("telo",11111,"title",22222))
post.enqueue(object : Callback<UserItem> {
override fun onFailure(call: Call<UserItem>, t: Throwable) {}
override fun onResponse(call: Call<UserItem>, response: Response<UserItem>) {
response.body()?.body?.let { Log.e("///////// OTVET ////////////", it) }
}
})
}
}
Answer the question
In order to leave comments, you need to log in
Obviously, if onResponse works, and something is displayed in the log, then the method works.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question