如何用Retrofit的GET方法解析参数?请求404问题排查
看起来你遇到了Retrofit传递路径参数时返回404的问题,我帮你梳理下可能的原因和对应的解决办法:
1. 先排查URL拼接是否正确
404的核心原因几乎都是请求的URL和API实际端点不匹配,你可以通过以下方式精准确认:
添加OkHttp日志拦截器查看实际请求URL
这是排查Retrofit请求问题最有效的方式,它会打印出完整的请求地址、请求头、响应内容等细节,帮你快速定位路径错误。
首先添加日志拦截器依赖(如果还没加):
implementation 'com.squareup.okhttp3:logging-interceptor:4.11.0'
然后修改Retrofit的构建代码,加入拦截器:
private void notificationJSON() { // 配置日志拦截器,打印完整请求响应细节 HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(logging) .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(RequestInterface.NOTIFICATION_URL) .client(client) // 注入配置好的OkHttpClient .addConverterFactory(GsonConverterFactory.create()) .build(); RequestInterface request = retrofit.create(RequestInterface.class); Call<List<GetNotification>> call = request.getNotification("1","10"); call.enqueue(new Callback<List<GetNotification>>() { @Override public void onResponse(Call<List<GetNotification>> call, Response<List<GetNotification>> response) { List<GetNotification> notification_pojo = response.body(); Log.d("Message", "code..."+response.code() + " message..." + response.message()+" body..."+response.body()); Log.d("Message pojo", "notification_pojo = " +notification_pojo); } @Override public void onFailure(Call<List<GetNotification>> call, Throwable t) { Log.e("onFailure ", t.getMessage()); } }); }
运行后查看日志,找到实际请求的URL,和你确认可用的API地址对比,看是否存在路径拼接错误(比如多了/少了路径段、baseUrl和@GET路径重复拼接等)。
2. 核对参数传递方式是否符合API要求
你的代码用了Path参数(把参数嵌入URL路径中),但要确认API是否真的采用这种方式接收参数:
- 如果API是用
?PageNumber=1&PageSize=10这种Query参数的方式,那你需要修改接口定义为:
public interface RequestInterface { String NOTIFICATION_URL = "http://xxxxx/api/"; @GET("Image/GetNotificationList") Call<List<GetNotification>> getNotification( @Query("PageNumber") int pageNumber, @Query("PageSize") int pageSize ); }
调用时依然传request.getNotification(1,10)即可,此时请求URL会自动拼接成http://xxxxx/api/Image/GetNotificationList?PageNumber=1&PageSize=10。
- 如果确实是Path参数,建议把参数类型从
String改为int(分页参数通常是整数类型,避免不必要的类型转换问题):
public interface RequestInterface { String NOTIFICATION_URL = "http://xxxxx/api/"; @GET("Image/GetNotificationList/{PageNumber}/{PageSize}") Call<List<GetNotification>> getNotification( @Path("PageNumber") int pageNumber, @Path("PageSize") int pageSize ); }
3. 确认BaseUrl的正确性
BaseUrl必须以/结尾,你的代码中NOTIFICATION_URL = "http://xxxxx/api/"是符合要求的,但要确保这个根路径确实是API的正确根地址。比如如果API的完整端点是http://xxxxx/Image/GetNotificationList/1/10,那你的BaseUrl应该是"http://xxxxx/",而不是"http://xxxxx/api/",这会导致路径多了api段,从而返回404。
总结
优先通过日志拦截器确认实际请求URL,这能快速定位到404的根源;然后根据API的实际参数接收方式调整接口定义,同时确保BaseUrl和路径拼接正确。
内容的提问来源于stack exchange,提问作者Vikas singh

