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

Android项目中Retrofit调用Laravel API的ApiService配置问题

解决Retrofit匹配Laravel路径参数的配置问题

你的后端接口使用的是路径参数形式(http://tfg.test/api/courses/26),而非查询参数(?course=26),只需修改ApiService中的注解即可适配:

修改后的ApiService代码

package com.example.retrofitpruebabuena.API;
import com.example.retrofitpruebabuena.models.Alumno;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface ApiService {
    // 用{course}作为路径占位符,对应后端的路径参数位置
    @GET("api/courses/{course}")
    Call<List<Alumno>> getStudents(@Path("course") int course);
}

核心修改说明

  • 调整@GET注解的路径:把api/courses/改为api/courses/{course},其中{course}是路径参数的占位符,会被实际传入的数值替换。
  • 替换参数注解:将@Query("course")换成@Path("course"),该注解会让Retrofit把传入的course值填充到路径占位符的位置,而非作为URL的查询参数。

其余代码(API类和MainActivity)无需改动,调用service.getStudents(25)时,会自动生成符合后端要求的请求URL:http://tfg.test/api/courses/25。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:52:38