You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Retrofit请求报HTTP 404错误排查求助(附实现代码)

问题分析与解决方案

核心问题:URL拼接错误导致404

你代码里的URL拼接逻辑完全错误,直接将https://jsonplaceholder.typicode.com/users/1和Params里的id、name、username等参数生硬拼接,最终请求的是类似https://jsonplaceholder.typicode.com/users/11AliceBobxxx的无效地址,这必然返回404。

jsonplaceholder的单个用户接口格式是GET /users/{id},只需传递用户ID即可,不需要把其他参数拼到路径里。


具体修复方案

方案1:优化API接口定义(推荐)

修改ProfileApiService,使用@Path指定用户ID,让Retrofit自动拼接正确路径:

interface ProfileApiService {
    @GET("users/{id}")
    suspend fun getUser(@Path("id") userId: Int): ProfileResponse
}

然后调整GetUserProfile的调用逻辑,只传递用户ID:

class GetUserProfile @Inject constructor(
    private val profileRepository: ProfileRepository
): MutableLiveData(){
    data class Params(
        val id: Int,
        val name: String,
        val username: String,
        val email: String,
        val phone: String,
    )

    fun execute(
        viewModel: ProfileDetailViewModel,
        input: Params?
    ): MutableLiveData<ProfileResponse> {
        return MutableLiveData<ProfileResponse>().apply {
            input?.let { params ->
                viewModel.viewModelScope.launch {
                    // 只传递id,其余参数不需要拼入URL
                    value = profileRepository.getUser(params.id)
                }
            }
        }
    }
}

注意:确保Constants.BASE_URL的值为"https://jsonplaceholder.typicode.com/"(结尾带斜杠)。

方案2:保留@Url构造正确完整URL

如果坚持使用@Url,需要手动构造合法的完整接口地址:

class GetUserProfile @Inject constructor(
    private val profileRepository: ProfileRepository
): MutableLiveData(){
    data class Params(
        val id: Int,
        val name: String,
        val username: String,
        val email: String,
        val phone: String,
    )

    fun execute(
        viewModel: ProfileDetailViewModel,
        input: Params?
    ): MutableLiveData<ProfileResponse> {
        return MutableLiveData<ProfileResponse>().apply {
            input?.let { params ->
                viewModel.viewModelScope.launch {
                    // 根据id构造正确的完整URL
                    val correctUrl = "https://jsonplaceholder.typicode.com/users/${params.id}"
                    value = profileRepository.getUser(correctUrl)
                }
            }
        }
    }
}

额外检查

  • 确认ProfileRepository中的getUser方法,只是直接调用ProfileApiService的对应方法,没有额外的URL拼接操作。
  • 若需要传递查询参数(比如筛选用户),应使用@Query注解,而非直接拼入路径。

内容的提问来源于stack exchange,提问作者biipek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 15:16:14