Не удалось получить isConnected: ошибка ECONNREFUSED (соединение отклонено) для Kotlin Запрос на модификацию поста - PullRequest
0 голосов
/ 01 апреля 2020

Я запускаю приложение Sample Spring Boot на локальном сервере (localhost) на порте 8080. Из клиентского приложения я пытался сделать запрос с помощью Kotlin Retrofit в моей Android Studio Эмулятор ,

Kotlin Код

interface RestApi {

    @Headers("Content-Type: application/json")
    @POST("users")
    fun addUser(@Body userData: CTUserInfo): Call<ResponseBody>
}


object ServiceBuilder {
    private val client = OkHttpClient.Builder().build()

    private val retrofit = Retrofit.Builder()
        .baseUrl("http://localhost:8080/")
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build()

    fun<T> buildService(service: Class<T>): T{
        return retrofit.create(service)
    }
}

class RestApiService {

    fun addUser(userData: CTUserInfo){

        val retrofit = ServiceBuilder.buildService(RestApi::class.java)

        retrofit.addUser(userData).enqueue(
            object : Callback<ResponseBody> {

                override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                    // failure
                    print("Failed") // getting t = below mentioned error
                }

                override fun onResponse( call: Call<ResponseBody>, response: Response<ResponseBody>) {

                    if (response.code() == 201) {
                        // user added
                        print("Success")
                    } else{
                        //user could not be added
                        print("Failed")
                    }
                }
            }
        )
    }
}

Я получаю сообщение об ошибке ниже:

java. net .ConnectException: ошибка подключиться к localhost / 127.0.0.1 (порт 8080) из /127.0.0.1 (порт 57452) через 10000 мс: isConnected fail: ECONNREFUSED (соединение отклонено)

Однако, когда я пытаюсь отправить сообщение из Почтальону это удается на http://localhost:8080/users.

Как решить?

Обновление

Мои Android файлы манифеста выглядят так,

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

    <application
            android:name=".BaseApplication"
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:usesCleartextTraffic="true"
            android:theme="@style/AppTheme">
            ...

Ответы [ 3 ]

0 голосов
/ 01 апреля 2020

Вы можете попробовать добавить в res / values ​​/ xml / network_security_config. xml

<?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">http://localhost:8080/</domain>
    </domain-config>
</network-security-config>

и ссылаться на это в манифесте внутри приложения тегов

<application
...
    android:networkSecurityConfig="@xml/network_security_config"
...
</application>
0 голосов
/ 02 апреля 2020

Наконец, я решил проблему, добавив фактическую машину IP, найденную, выполнив следующие команды в bash

  1. Ma c - ifconfig
  2. Windows - ipconfig /all

Пример,

private val retrofit = Retrofit.Builder()
    .baseUrl("http://192.168.64.1:8080/")
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build()
0 голосов
/ 01 апреля 2020

Вы добавили разрешение inte rnet в свой манифест? и вы должны добавить clear teext trafi c, если вы тестируете на новом устройстве, API которого - P ie. как это:

 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:usesCleartextTraffic="true">
...