Home > Software engineering >  callback always fails with retrofit url
callback always fails with retrofit url

Time:06-17

this is the mainactivity

val url:String="http://api.brainshop.ai/get?bid=167083&key=jIpZgrpRgALYSZ72&uid=[uid]&msg=" message
            val BASE_URL="http://api.brainshop.ai/"
            val retrofit=Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
            val retrofitAPI=retrofit.create(RetrofitAPI::class.java)
            val call:retrofit2.Call<MsgModal> = retrofitAPI.getMessage(url)

            call.enqueue(object: Callback<MsgModal>{
                override fun onResponse(call: retrofit2.Call<MsgModal>, response: Response<MsgModal>) {
                    val modal: MsgModal = response.body()!!
                    Toast.makeText(applicationContext,"bsh", Toast.LENGTH_SHORT).show()
                    messageModalArrayList.plusAssign(ChatsModal(modal.cnt, BOT_KEY))
                    Toast.makeText(applicationContext, modal.cnt, Toast.LENGTH_SHORT).show()
                    chatRVAdapter.notifyDataSetChanged()
                }
                override fun onFailure(call: retrofit2.Call<MsgModal>, t: Throwable) {
                    messageModalArrayList.add(ChatsModal("please revert your question",BOT_KEY))
                    chatRVAdapter.notifyDataSetChanged()
                }

            })

Msgmodal.kt

class MsgModal (
    var cnt: String
        )

retroapi interface

interface RetrofitAPI {
    @GET
    fun getMessage(@Url url: String ): Call<MsgModal>
}

there is no error in the logcat...and the bot message is always directed to onfailure part in callback

CodePudding user response:

You can fix that by simply adding

android:usesCleartextTraffic="true"

To your <application> tag in the manifest

CodePudding user response:

So you have to : Create file res/xml/network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">Your URL(ex: 127.0.0.1)</domain>
    </domain-config>
</network-security-config>

and on your manifest :

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:networkSecurityConfig="@xml/network_security_config"
        ...>
        ...
    </application>
</manifest> 
  • Related