flask + retrofit in kotlin cannot acces API endpoint with IP address (Failed to connect to /127.0.0.1:5000)

Viewed 592

I created a api in flask which returns longitude, latitude and id. And I want to get that response within my own android device. I tested the api with postman, and I can access it via phone browser too with
URL = "http://192.168.0.185:3000"

Trying to access it with retrofit produces me long error track I can't figure out.

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.posttest, PID: 2144
    java.net.ConnectException: Failed to connect to /127.0.0.1:5000
        at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.kt:285)
        at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:195)
        at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:249)
        at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:108)
        at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:76)
        at okhttp3.internal.connection.RealCall.initExchange$okhttp(RealCall.kt:245)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:32)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:82)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
        at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:197)
        at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:502)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)
     Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 5000) from /127.0.0.1 (port 37738) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused)

I tried the approach of running the app on my emulator and then trying to access it with
URL ="http://10.0.2.2:3000"

It still gives me error. How can I achieve that? Here is how my api response looks like: enter image description here enter image description here

My Flask server code is very simple

app = Flask(__name__)
api = Api(app)
api.add_resource(LocationValues, '/adamapi')

@app.route('/')
def hello():
    return 'Hello,REST'

if __name__ == '__main__':
    app.run("0.0.0.0",debug=True,port= 3000)

Resource.py

    def get(self):
        connection = sqlite3.connect('db.sqlite')
        cursor = connection.cursor()
        query = "SELECT * FROM location WHERE id = 1"
        result = cursor.execute(query).fetchone()
        connection.close()
        if result:
            return {'item': {'measure_id': result[0], 'longitude': result[1], 'latitude': result[2]}}
        return {"message": "Wrong get request"}, 400

And Kotlin files
Contants.kt

class Constants {
    companion object{
        const val BASE_URL = "http://192.168.0.185:3000"
    }
}

DataClass.kt

data class Post(
    val item: Item
)

data class Item(
    val latitude: Double,
    val longitude: Double,
    val measure_id: Int
)

SimpleApi.kt

interface SimpleApi {
    @GET("adamapi")
    suspend fun getPost(): Post
}

Repository.kt

class Repository {
    suspend fun getPost(): Post {
        return RetrofitInstance.api.getPost()

    }
}

RetrofitInstance.kt

object RetrofitInstance {

    private val retrofit  by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()

    }
    val api:SimpleApi by lazy {
        retrofit.create(SimpleApi::class.java)
    }
}

MainViewModel and MainViewModelFactory classes in .kt

class MainViewModel(private  val repository: Repository):ViewModel() {
    val myResponse: MutableLiveData<Post> = MutableLiveData()
    fun getPost (){
        viewModelScope.launch {
            val response :Post = repository.getPost()
            myResponse.value = response
        }
    }
}


class MainViewModelFactory (private val repository:Repository):ViewModelProvider.Factory {
    override fun <T: ViewModel?> create (modelClass: Class<T>):T{
        return MainViewModel(repository) as T
    }
}

I added internet permission on Manifest file. Also this explanation here wasn't working on my device as well -> https://medium.com/analytics-vidhya/how-to-make-client-android-application-with-flask-for-server-side-8b1d5c55446e
Both my devices are using Wifi.

Error: enter image description here

Update: Following @martin-zeitler answer It now works on emulator. But using my ipv4 address still gives errors.
enter image description here enter image description here enter image description here

2 Answers

The stack-trace obviously doesn't match the code.

When intending to connect to an IP address, one should state it:

companion object {
    const val BASE_URL = "http://10.0.2.2:3000/"
}

Then add an alternate configuration at src/debug/res/xml/network_security_config.xml:

<?xml version="1.0" encoding="utf-8"?>
<!-- Debug Network Security Configuration -->
<network-security-config
    xmlns:tools="http://schemas.android.com/tools">
    <base-config
        tools:ignore="InsecureBaseConfiguration"
        cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system"/>
        </trust-anchors>
    </base-config>
</network-security-config>

Also to be referenced the AndroidManifest.xml:

<application
    ...
    android:networkSecurityConfig="@xml/network_security_config" />

This is required to permit plain-text HTTP traffic while debugging.

in RetrofitInstance.kt add "/" after BASE_URL so it will look like this:

private val retrofit  by lazy {
    Retrofit.Builder()
        .baseUrl(BASE_URL + "/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()

}
Related