Retrofit Answer returning null with code 406 Not Acceptable

Asked

Viewed 144 times

1

Talk personal, I’m using Retrofit2 with Kotlin and I’m trying to perform a POST request where a Json will be returned.

The request is made and the server part works (register the user), however when I will treat the Answer, it always returns null (with code 406 Not Acceptable)

Request made on Postman: Requisição feita no Postman inserir a descrição da imagem aqui

Retrofitconfig.kt

class RetrofitConfig(baseUrl: String) {
private val gson = GsonBuilder().create()
private val httpClient = OkHttpClient.Builder()
private val retrofitBuilder = Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(GsonConverterFactory.create(gson))
private var retrofit = retrofitBuilder.build()

fun loginService(): LoginService {
    return createService(LoginService::class.java)
}

fun registerService(): RegisterService {
    return createService(RegisterService::class.java)
}

fun <S> createService(serviceClass: Class<S>): S {
    retrofitBuilder.client(httpClient.build())
    retrofit = retrofitBuilder.build()
    return retrofit.create(serviceClass)
}

Registerservice.kt & Loginservice.kt

interface RegisterService {
    @POST("registrar/")
    fun registrar(@Body usuario: Usuario): Call<AuthResponse>
}
interface LoginService {
    @POST("login/")
    fun login(@Body usuario: Usuario): Call<AuthResponse>
}

Making the Request (both register and log in)

override fun logIn(usuario: Usuario) {
    val call = RetrofitConfig(baseUrl).loginService().login(usuario)

    call.enqueue(object : Callback<AuthResponse> {
        override fun onFailure(call: Call<AuthResponse>?, t: Throwable?) {
            Toast.makeText(this@AuthFragmentRouterActivity, "Sem conexão com a internet.", Toast.LENGTH_LONG).show()
        }
        override fun onResponse(call: Call<AuthResponse>?, response: Response<AuthResponse>?) {
            val body = response?.body()
            if (response?.isSuccessful == true) {
                if (body!!.sucesso) {
                    usuario.pontuacao = body.pontuacao
                    val it = Intent(this@AuthFragmentRouterActivity, QuizFragmentRouterActivity::class.java)
                    it.putExtra("usuario", Gson().toJson(usuario))
                    startActivity(it)
                    finish()
                } else Toast.makeText(this@AuthFragmentRouterActivity, body.mensagem, Toast.LENGTH_LONG).show()
            } else Toast.makeText(this@AuthFragmentRouterActivity, "Ocorreu um erro.", Toast.LENGTH_LONG).show()
        }
    })
}
override fun signUp(usuario: Usuario) {
    val call = RetrofitConfig(baseUrl).registerService().registrar(usuario)

    call.enqueue(object : Callback<AuthResponse> {
        override fun onFailure(call: Call<AuthResponse>?, t: Throwable?) {
            Toast.makeText(this@AuthFragmentRouterActivity, "Sem conexão com a internet.", Toast.LENGTH_LONG).show()
        }
        override fun onResponse(call: Call<AuthResponse>?, response: Response<AuthResponse>?) {
            val body = response?.body()
            Log.d("Quiz", "Response: ${response?.code()}")
            if (response?.isSuccessful == true) {
                if (body!!.sucesso) {
                    val it = Intent(this@AuthFragmentRouterActivity, QuizFragmentRouterActivity::class.java)
                    it.putExtra("usuario", Gson().toJson(usuario))
                    startActivity(it)
                    finish()
                } else Toast.makeText(this@AuthFragmentRouterActivity, body.mensagem, Toast.LENGTH_LONG).show()
            } else Toast.makeText(this@AuthFragmentRouterActivity, "Ocorreu um erro.", Toast.LENGTH_LONG).show()
        }
    })
}
  • the mapping is "register", but you use "login" in Postman

  • I get the same result in both registration and login.

  • post the result, and where the login mapping is?

  • updated prints and codes

1 answer

1


Your server is returning this error because it did not receive the Accept parameter in the header specifying which type of return is expected.

In your Retrofit interface add the following:

@Headers({
    "Content-Type: application/json;charset=utf-8",
    "Accept: application/json",
    "User-Agent: Android"
})

Reference to answer on ONLY.

  • That’s right, but I also had to change the shape that passed the parameters, instead of sending an object like Body, I sent the separate attributes as Field. Resolved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.