Retrofit2 GET请求异常求助:调试时代码无法执行至调用行
解决你的Retrofit2请求问题
Hey there! Let's work through why your Retrofit call isn't executing properly. I've spotted a few key issues in your code that are almost certainly causing the problem—let's fix them step by step:
1. 错误使用注解处理查询参数
你当前的接口用@Path来处理URL里的date参数,但date=属于查询参数(URL中?后面的部分),@Path是用来替换URL路径中的占位符(比如/api/{id}/data这种结构)。正确的做法是用@Query注解:
修改JsonGet.java接口:
package appka.matej.lukas.pizzerias; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; public interface JsonGet { @GET("api/pizzerias.php") Call<List<PostJson>> get_json(@Query("date") String user); }
2. 实体类不符合Gson解析要求
你的PostJson类缺少无参构造函数,而且没有显式的字段映射注解,这会导致Gson无法正确解析JSON数据:
修改PostJson.java:
package appka.matej.lukas.pizzerias; import com.google.gson.annotations.SerializedName; public class PostJson { @SerializedName("name") // 确保和返回JSON中的字段名完全匹配 private String name; // Gson必须要有无参构造函数来实例化对象 public PostJson() {} public PostJson(String name) { this.name = name; } // 添加getter方法,方便后续获取数据 public String getName() { return name; } }
3. 配置Android网络相关权限与明文请求限制
- 首先在
AndroidManifest.xml中添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />
- 如果你的设备是Android 9(API 28)及以上,系统默认禁止明文HTTP请求(你的baseUrl是
http://),需要配置网络安全规则:- 在
res/xml目录下创建network_security_config.xml(如果没有xml目录就新建一个):
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">matej.martintoth.sk</domain> </domain-config> </network-security-config>- 在
AndroidManifest.xml的<application>标签中添加引用:
android:networkSecurityConfig="@xml/network_security_config" - 在
4. 添加调试日志排查问题
在onFailure回调中打印错误堆栈信息,这样你能在Logcat里看到具体的错误原因(比如网络连接失败、JSON解析错误等):
@Override public void onFailure(Call<List<PostJson>> call, Throwable t) { Toast.makeText(getApplicationContext(), "KO", Toast.LENGTH_SHORT).show(); // 打印错误日志到Logcat t.printStackTrace(); }
按照这些步骤修改后,你的Retrofit请求应该能正常执行了。如果还有问题,查看Logcat里的错误信息,就能更精准地定位问题啦!
内容的提问来源于stack exchange,提问作者Edering
相关产品推荐
相关产品推荐

