我正在本地计算机服务器(localhost)的端口8080上运行Sample Spring Boot应用程序。从客户端应用程序,我试图通过Kotlin Retrofit在Android Studio 仿真器中发出发布请求>,
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:10000毫秒后无法从/127.0.0.1(端口57452)连接到localhost / 127.0.0.1(端口8080):isConnected失败:ECONNREFUSED(连接被拒绝)
但是,当我尝试从Postman发帖时,它会在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">
...
答案 0 :(得分:0)
您是否已在清单中添加了许可互联网? 如果您在API为Pie的新设备上进行测试,则必须添加清晰的teext流量。像这样:
<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">
答案 1 :(得分:0)
您可以尝试添加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>
答案 2 :(得分:0)
最后,我通过添加在bash中运行以下命令找到的实际机器IP
解决了该问题
ifconfig
ipconfig /all
示例
private val retrofit = Retrofit.Builder()
.baseUrl("http://192.168.64.1:8080/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()