我正在尝试对Kotlin Retrofit进行发布请求,
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(连接被拒绝)
但是,当我尝试从邮递员发帖时,它会在http://localhost:8080/users
上成功发送。
如何解决?
您是否在清单中添加了权限互联网?如果您在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">