Reputation: 155
I have a flask restful server which gives me some JSON. I try to use okhttp to get that json in my app but it doesn't work. It always fails. I tried with the Wikipedia API and it works. My server runs on localhost and I use 10.0.2.2 in my application. The weirdest thing is that 10.0.2.2 works in the emulator browser and it shows me the JSON but it won't work in my application.
Here is the method that is called in my main activity:
fun fetchJson() {
val url = "http://10.0.2.2:5000/users"
val request = Request.Builder().url(url).build()
println(request.url())
val client = OkHttpClient()
client.newCall(request).enqueue(object: Callback {
override fun onFailure(call: Call, e: IOException) {
println("Failed to execute")
}
override fun onResponse(call: Call, response: Response) {
val body = response.body()?.string()
println(body)
}
})
}
It always prints "Failed to execute"
Note: I added the INTERNET permission in the manifest.
Upvotes: 2
Views: 1680
Reputation: 155
@Xvolks suggestion to print the exception helped. It was because in API level 28, the cleartext support is disabled. This is the answer that helped me:
Android 8: Cleartext HTTP traffic not permitted
Upvotes: 2