Answer the question
In order to leave comments, you need to log in
Retrofit kotlin request code fails, why?
A simple request to get data in json format. The problem is that when the request is successfully (!) sent, the onResponce code is not executed at all - no result, no error, no exceptions - nothing, as if the program simply skips these lines. At the same time, onFailure() in the case of a knowingly broken request (for example, a knowingly broken link) is executed! Checked it many times. I suspect that the problem is in the data from the server - the server does not return pure json, but json inside the , . Could this be a problem?
Interface:
import retrofit2.Call
import retrofit2.http.GET
interface OrgList {
@GET("test.php/")
fun getcompanyes(): Call<List<Company?>?>
}
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitClient {
var retrofit = Retrofit.Builder()
//Адрес источника публиковать не могу, поэтому заменил
.baseUrl("https://domain.ru/text/")
.addConverterFactory(GsonConverterFactory.create())
.build()
var companyes = retrofit.create(OrgList::class.java)
}
val headtext: TextView = findViewById(R.id.textView)
try {
val orgs: Call<List<Company?>?>? =
RetrofitClient.companyes.getcompanyes()
orgs?.enqueue(object : Callback<List<Company?>?> {
override fun onFailure(call: Call<List<Company?>?>, t: Throwable) {
//Без проблем выполняется, если ссылка baseUrl битая (например, http вместо https)
Toast.makeText(applicationContext, "Failed callback! ${t.message}", Toast.LENGTH_LONG).show()
}
override fun onResponse(
@NonNull call: Call<List<Company?>?>,
@NonNull response: Response<List<Company?>?>
) {
/*Ничего из этого не выполняется, ошибка не выводится, onFailure тоже не выполняется - просто ничего не происходит*/
headtext.text = response.body()?.toString()
Toast.makeText(applicationContext, response.body()?.toString(), Toast.LENGTH_LONG).show()
}
} )
} catch (e: Exception) {
headtext.text = "Exc: $e"
}
Answer the question
In order to leave comments, you need to log in
First, there is no need to write nullable types in the interface.
Call<List<Company?>?>
replace with
Call<List<Company>>
Well, the response from the server should come in json format, and not some tags.
If you want to clean it from unnecessary tags before parsing the result from the server, then:
interface OrgList {
@GET("test.php/")
fun getcompanyes(): Call<List<Company?>?>
}
interface OrgList {
@GET("test.php/")
fun getcompanyes(): Call<ResponseBody>
}
You need to log the response from the server. You can use several tools for this:
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question