已解决:愚蠢的错误,我有https://foo.foo.com:433而不是https://foo.foo.com:443 ...
我已经实现了Retrofit,我正尝试将JSON数据作为JsonObject发送POST请求。它无法正常工作,并且出现“连接超时”失败,但是我可以通过Postman发送POST请求而没有问题。起初我以为是因为标头,所以我尝试使用Interceptor并使用@Header而不是@Headers。谢谢您的帮助。
邮递员
从HttpLoggingInterceptor()登录
Jun 30, 2018 10:22:09 AM okhttp3.internal.platform.Platform log
INFO: --> POST https://foo.foo.com:433/
Jun 30, 2018 10:22:09 AM okhttp3.internal.platform.Platform log
INFO: Content-Type: application/json
Jun 30, 2018 10:22:09 AM okhttp3.internal.platform.Platform log
INFO: Content-Length: 132
Jun 30, 2018 10:22:09 AM okhttp3.internal.platform.Platform log
INFO:
Jun 30, 2018 10:22:09 AM okhttp3.internal.platform.Platform log
INFO: {"transport":"web","userId":"ggrojeomieje2","moduleId":105,"moduleName":"signal","moduleVersion":1,"operation":"signal","params":{}}
Jun 30, 2018 10:22:09 AM okhttp3.internal.platform.Platform log
INFO: --> END POST (132-byte body)
Jun 30, 2018 10:22:19 AM okhttp3.internal.platform.Platform log
failure connect timed out [Ljava.lang.StackTraceElement;@3850debc
INFO: <-- HTTP FAILED: java.net.SocketTimeoutException: connect timed out
Api界面
interface ApiEndpoints {
@POST("/")
@Headers("Content-Type: application/json")
fun sendRequest(@Body json: PostModel): Call<ResponseModel>
}
改造客户端
class ApiClient {
val service = Retrofit.Builder()
.baseUrl("https://foo.foo.com:433")
.client(client) // Implement HttpLoggingInterceptor()
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiEndpoints::class.java)
}
Api通话
val test = ApiClient().service.sendRequest(
PostModel("web",
"ggrojeomieje2",
105,
"signal",
1,
"signal",
Params())
)
test.enqueue(object : Callback<ResponseModel> {
override fun onResponse(call: Call<ResponseModel>?, response: Response<ResponseModel>?) {
println("response " + response?.body()?.params?.timestamp.toString())
}
override fun onFailure(call: Call<ResponseModel>?, t: Throwable?) {
println("failure " + t?.message.toString())
}
})
模型
data class ResponseModel(val params: Params?)
data class PostModel(var transport: String? = null,
var userId: String? = null,
var moduleId: Int? = 0,
var moduleName: String? = null,
var moduleVersion: Int? = 0,
var operation: String? = null,
var params: Params?
)
data class Params(var timestamp: Unit? = null)
回复
{"params":{"timestamp":1.530346984546E9}}
答案 0 :(得分:1)
尝试在OkHttpClient
中设置超时值。
val client = OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
还尝试更改请求主体类型,例如x-www-form-urlencoded
或form-data
和标头,例如@Headers({"content-type: application/json"})
或
检查是否存在与网络相关的问题,或者只是尝试一些简单的GET
方法也失败了。
答案 1 :(得分:0)
愚蠢的错误,我有https://foo.foo.com:433而不是https://foo.foo.com:443 ...