0

Estou tentando acessar o conteúdo json dentro do body() através do retrofit. Preciso da "url" em String. O que está faltando no meu código?

Depurando o código vi que o response.body() está retornando o seguinte resultado:

Response{protocol=h2, code=200, message=, url=https://api.photos/public/500x500/czM6Ly9waG90b3MuZW5qb2VpLmNvbS5ici9wcm9kdWN0cy84MTI1OTIvNmE1ZDFhOTgyYjAwYjdjZDU3MjJhYzQ0NzE3YjVhZGMuanBn}

Eu não estou conseguindo acessar a url digitando response.body().url.toString()

InterfaceApi:

interface ImageService {

    @GET("500x500/czM6Ly9waG90b3MuZW5qb2VpLmNvbS5ici9wcm9kdWN0cy84MTI1OTIvNmE1ZDFhOTgyYjAwYjdjZDU3MjJhYzQ0NzE3YjVhZGMuanBn")
    fun image(): Call<String>

}

Model Image:

class Image<T>{
    val response: String = ""
    var protocol: String = ""
    var message: String = ""
    var url: String = ""


}

Retrofit:

class NetworkUtils private constructor(){


    companion object {

        private lateinit var retrofit: Retrofit
        private fun getRetrofitInstance(): Retrofit {
            val httpClient = OkHttpClient.Builder()
            if(!::retrofit.isInitialized){
                retrofit = Retrofit.Builder()
                    .baseUrl(Constants.BASE_URL_IMG)
                    .client(httpClient.build())
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()

            }
            return retrofit
        }

        fun <T> createService(serviceClass: Class<T>): T{
            return getRetrofitInstance().create(serviceClass)
        }

    }
}

MainActivity:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_fragment)
        setSupportActionBar(findViewById(R.id.toolbar_edit))


        val remote = NetworkUtils.createService(ImageService::class.java)
        val call: Call<String> = remote.image()
        val response = call.enqueue(object : Callback<String> {
            override fun onResponse(call: Call<String>, response: Response<String>) {
                Log.d("ok", response.body().toString())
            }

            override fun onFailure(call: Call<String>, t: Throwable) {
                Log.d("error", t.toString())
            }

        })

    }
}

Dependencias Gradle:

dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation "androidx.cardview:cardview:1.0.0"
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
    implementation "org.koin:koin-android:2.2.0"
    implementation "org.koin:koin-android-scope:2.2.0"
    implementation "org.koin:koin-android-viewmodel:2.2.0"
    implementation 'com.squareup.retrofit2:retrofit:2.8.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.9.0'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.2'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
    implementation 'com.squareup.picasso:picasso:2.71828'
    apply plugin: 'kotlin-android-extensions'
    implementation 'com.squareup.retrofit2:converter-scalars:2.8.0'


}

Testei a requisição no Postman e está tudo ok, acredito que o problema seja na minha aplicação

2 Respostas 2

0

Você precisa passar o tipo correto de retorno da interface do seu serviço:

interface

ImageService {
    @GET("500x500/czM6Ly9waG90b3MuZW5qb2VpLmNvbS5ici9wcm9kdWN0cy84MTI1OTIvNmE1ZDFhOTgyYjAwYjdjZDU3MjJhYzQ0NzE3YjVhZGMuanBn")
    fun image(): Call<Image>
}

Model Image:

class Image {
    val response: String = ""
    var protocol: String = ""
    var message: String = ""
    var url: String = ""
}
0

Resolvi esse e outros problemas de acesso ao result utilizando o Coroutines. É mais fácil de usar com poucas linhas de código.

Segui esse tutorial aqui

Substitui o call.enqueue por:

fun callImage() {

        val apiService = NetworkUtils.createServiceImage(ApiService::class.java)

        GlobalScope.launch(Dispatchers.IO) {
            val result = apiService.image().await()
            Log.d("Result url image = ", result.url)

        }

Gerei a class automaticamente usando o plugin JSON to Kotlin class:

class Images {
    val response: String = ""
    var protocol: String = ""
    var message: String = ""
    var url: String = ""
}

E alterei a Interface:

interface ApiService {

    @GET("500x500/czM6Ly9waG90b3MuZW5qb2VpLmNvbS5ici9wcm9kdWN0cy81NjEyNS9mZjU3NTFmMDc3NjYxMzllOTllODA4OTgwMDQ4YWVkYi5qcGc")
    fun image(): Call<Images>
}

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .