如何用Retrofit构造locations=lat,lon格式的GET请求?
解决GET请求中List参数生成逗号分隔格式的问题
默认情况下,Retrofit(假设你使用的是这个框架)处理@Query注解的List类型参数时,会将其拆分为多个同名的URL参数(如locations=lat&locations=lon)。要实现locations=lat,lon的格式,有以下几种可行方案:
方案1:手动拼接成字符串(最简单直接)
放弃使用List<Double>,直接传递拼接好的逗号分隔字符串:
@GET("your-target-endpoint") Call<YourResponseModel> fetchLocations(@Query("locations") String locationStr); // 调用示例 double lat = 39.9042; double lon = 116.4074; String formattedLocation = lat + "," + lon; yourApiService.fetchLocations(formattedLocation);
方案2:自定义Converter自动转换List
如果希望保留List<Double>的参数形式,可以通过自定义Converter让Retrofit自动将列表转为逗号分隔字符串:
- 实现字符串转换逻辑:
public class ListDoubleToCsvConverter implements Converter<List<Double>, String> { @Override public String convert(List<Double> values) throws IOException { if (values == null || values.isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < values.size(); i++) { sb.append(values.get(i)); if (i != values.size() - 1) { sb.append(","); } } return sb.toString(); } }
- 在Retrofit构建时注册该Converter:
Retrofit retrofit = new Retrofit.Builder() .baseUrl("your-base-url/") .addConverterFactory(GsonConverterFactory.create()) .addConverterFactory(new Converter.Factory() { @Override public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) { // 判断是否为List<Double>类型的参数 if (type instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) type; if (paramType.getRawType().equals(List.class) && paramType.getActualTypeArguments()[0].equals(Double.class)) { return new ListDoubleToCsvConverter(); } } return super.stringConverter(type, annotations, retrofit); } }) .client(yourOkHttpClient) .build();
- 正常使用
List<Double>参数即可:
@GET("your-target-endpoint") Call<YourResponseModel> fetchLocations(@Query("locations") List<Double> locations); // 调用示例 List<Double> locationList = Arrays.asList(39.9042, 116.4074); yourApiService.fetchLocations(locationList);
方案3:使用encoded参数标记已格式化字符串
如果需要自行处理编码(比如参数包含特殊字符),可以用encoded=true让Retrofit不对字符串做额外编码:
@GET("your-target-endpoint") Call<YourResponseModel> fetchLocations(@Query(value = "locations", encoded = true) String locationStr); // 调用示例(若有特殊字符需自行编码) String formattedLocation = URLEncoder.encode(lat + "," + lon, StandardCharsets.UTF_8.name()); yourApiService.fetchLocations(formattedLocation);
内容的提问来源于stack exchange,提问作者Neyross
相关产品推荐
相关产品推荐

