获取响应{protocol = http / 1.1,代码= 404,消息=未找到,网址= {https://test.test.com/service/one}
该网址是正确的,因为邮递员可以正常工作。
我曾尝试调查此错误,但URL返回的大多数内容都是正确的。错误本身是模糊的。
启动它的代码。该构建器是有效的json字符串。我已经在邮递员中测试过。
CoroutineScope(Dispatchers.Default).launch {
val call = submitService.submitCarton(builder.toString())
Log.d("submit", "begining")
withContext(Dispatchers.Main) {
if (call.isSuccessful) {
Log.d("submit",call.body() as String)
} else {
Log.d("submit", "else....")
}
}
}
服务工厂:
fun makeSubmitService() : SubmitService{
val url = "https://test.test.com/service/"
return Retrofit.Builder().baseUrl(url)
.client(okHttpClient).addConverterFactory(GsonConverterFactory.create())
.build().create(SubmitService::class.java)
}
界面:
interface SubmitService {
@POST("one")
suspend fun submitCarton(@Body json: String): Response<myModel>
}
预期结果是一个json响应,但是我还没走那么远。
edit:我创建了一个okhttpclient并做了一个请求手册,并收到一条200 ok的消息。
我的测试代码
val JSON = MediaType.parse("application/json; charset=utf-8")
val client = OkHttpClient()
val body = "some json"
val requestBody = RequestBody.create(JSON, body)
val request = Request.Builder()
.url("https://test.test.com/service/one")
.post(requestBody)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(request: Request, e: IOException) {
Log.e("test", e.toString())
}
@Throws(IOException::class)
override fun onResponse(response: Response) {
Log.d("test", response.toString())
}
})
答案 0 :(得分:0)
自己解决。
问题很愚蠢,即使Web服务返回错误消息,retrofit2也给出404。
已添加
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
private val interceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
private val okHttpClient = OkHttpClient().newBuilder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.addInterceptor(interceptor)
.build()
发现改型发送的是未格式化的字符串
"{ \"all my json filled with \" }"
代替
{ json }
通过添加
对其进行了修复.addConverterFactory(ScalarsConverterFactory.create())
到我的服务工厂
对于任何想知道为什么我基本上将json创建为字符串而不是使用JSON对象的人来说,是因为与我交谈的服务真的希望它以非常特定的顺序排列,而JSON只是不在乎它它也希望它也看起来像JSON ...