Retrofit请求接口中如何正确设置参数?
正确传递Retrofit查询参数的方式
嘿,你猜的思路方向没错,但Retrofit有更规范灵活的写法来处理这类?key=value形式的查询参数,不用直接把参数硬编码在@GET的路径字符串里~
方式一:单个查询参数(匹配你的?id=1001场景)
直接在接口方法的参数上添加@Query注解,Retrofit会自动帮你把参数拼接到请求URL的查询部分:
public interface GetDataService { @GET("/news") Call<ItemAPI> getAllItems(@Query("id") int itemId); }
调用的时候传入对应数值即可:
GetDataService service = retrofit.create(GetDataService.class); Call<ItemAPI> call = service.getAllItems(1001); // 后续发起请求逻辑...
这样最终生成的请求URL就是/news?id=1001,完全符合你的需求。
方式二:多查询参数/灵活参数场景
如果后续需要传递多个查询参数(比如/news?id=1001&type=top),可以给每个参数都加上@Query注解:
public interface GetDataService { @GET("/news") Call<ItemAPI> getAllItems(@Query("id") int itemId, @Query("type") String newsType); }
要是参数数量不确定、需要更灵活的传参方式,还可以用@QueryMap传递一个Map集合:
public interface GetDataService { @GET("/news") Call<ItemAPI> getAllItems(@QueryMap Map<String, Object> params); }
调用时构建Map传入参数:
Map<String, Object> params = new HashMap<>(); params.put("id", 1001); params.put("type", "top"); Call<ItemAPI> call = service.getAllItems(params);
为什么不推荐直接拼在@GET路径里?
你之前猜想的@GET("/news?id={id}")写法虽然能运行,但不符合Retrofit的设计规范——路径占位符{}是用来替换URL路径部分的(比如/news/{id}这种路径参数),不是处理查询参数的。而且这种硬编码方式面对可选参数时会很麻烦,用@Query的话可以直接传null(Retrofit会自动忽略null的查询参数),比如:
public interface GetDataService { @GET("/news") Call<ItemAPI> getAllItems(@Query("id") Integer itemId); // 用包装类允许传null } // 调用时不传id,最终URL就是/news,不会带?id参数 Call<ItemAPI> call = service.getAllItems(null);
内容的提问来源于stack exchange,提问作者flex_grigorowicz
相关产品推荐
相关产品推荐

