【问题标题】:kotlin: retrofit2 getting 404 url not found errorkotlin:retrofit2 得到 404 url​​ not found 错误
【发布时间】:2019-10-01 18:32:15
【问题描述】:

得到响应{protocol=http/1.1, code=404, message=Not Found, url=https://test.test.com/service/one}

网址正确,因为邮递员工作正常。

我已尝试调查此错误,但大多数返回的 URL 都是正确的。并且错误本身是模糊的。

启动它的代码。 builder 是一个有效的 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 响应,但我没有走那么远。

编辑:我创建了一个 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())
        }

    })

【问题讨论】:

    标签: kotlin retrofit2


    【解决方案1】:

    自己解决了。

    问题很愚蠢,即使 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...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-12
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 2015-03-20
      相关资源
      最近更新 更多