Android Retrofit实现GET请求返回空对象问题求助
问题分析与解决方案
核心问题
你遇到的问题根源在于GET请求的参数传递方式不匹配:
- Postman中你是把参数放在请求Body里发送GET请求(虽然不符合HTTP规范,但Postman支持这种非常规用法)
- 而Retrofit中用
@Query是把参数拼接到URL的查询字符串中,服务端实际是从请求Body读取参数,自然找不到对应值,返回空对象。
另外你的代码里还有两处明显的类型错误,也会导致请求异常:
boolean cod = "1";:boolean类型不能赋值字符串,类型不匹配float weight = "1";:float类型不能赋值字符串,类型不匹配
解决方案
方案1:按服务端要求用GET请求携带Body(适配Postman的调用方式)
Retrofit默认不支持GET请求带Body,需要通过@HTTP注解自定义请求:
- 创建参数实体类
public class ServiceabilityParams { @SerializedName("pickup_postcode") private String pickupPostcode; @SerializedName("delivery_postcode") private String deliveryPostcode; @SerializedName("cod") private String cod; @SerializedName("weight") private String weight; // 构造方法 public ServiceabilityParams(String pickupPostcode, String deliveryPostcode, String cod, String weight) { this.pickupPostcode = pickupPostcode; this.deliveryPostcode = deliveryPostcode; this.cod = cod; this.weight = weight; } }
- 修改Retrofit接口
public interface ShipRocketServiceAbilityInterface { @HTTP(method = "GET", path = "courier/serviceability/", hasBody = true) Call<ShipRocketServiceabilityResponse> getService(@Body ServiceabilityParams params); }
- 修正调用代码的类型错误
// 修正类型错误,统一用String匹配参数格式 String pickupPostcode = "600114"; String deliveryPostcode = "600125"; String cod = "1"; String weight = "1"; Call<ShipRocketServiceabilityResponse> service = shipRocket.getService(new ServiceabilityParams(pickupPostcode, deliveryPostcode, cod, weight)); service.enqueue(new Callback<ShipRocketServiceabilityResponse>() { @Override public void onResponse(Call<ShipRocketServiceabilityResponse> call, Response<ShipRocketServiceabilityResponse> response) { if (response.isSuccessful() && response.body() != null) { String currency = response.body().getCurrency(); // 处理返回数据 } else { Log.d("TAG", "请求失败,响应码:" + response.code()); } } @Override public void onFailure(Call<ShipRocketServiceabilityResponse> call, Throwable t) { Log.d("TAG","请求失败:" + t.getMessage()); } });
方案2:改用URL查询参数传递(如果服务端支持)
如果服务端实际兼容URL查询参数的传递方式,只需修正代码中的类型错误即可:
- 保留原接口不变
- 修正调用代码的类型错误
String pickupPostcode = "600114"; String deliveryPostcode = "600125"; String cod = "1"; // 改为String类型,匹配接口参数类型 String weight = "1"; // 改为String类型,或接口参数改为float时用float weight = 1.0f; Call<ShipRocketServiceabilityResponse> service = shipRocket.getService(pickupPostcode,deliveryPostcode,cod,weight); // 后续回调代码同方案1
辅助排查建议
添加Retrofit日志拦截器,查看完整的请求/响应详情,确认参数是否正确传递:
OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("你的BaseURL") .client(client) .addConverterFactory(GsonConverterFactory.create()) .build();
内容的提问来源于stack exchange,提问作者AMRESWAR V
相关产品推荐
相关产品推荐

