创建API接口
// getData.php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "myDB"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed"); } $sql = "SELECT FROM users"; $result = $conn->query($sql); $data = array(); while ($row = $result->fetch_assoc()) { $data[] = $row; } echo json_encode($data); $conn->close();
部署服务器
在 AndroidManifest.xml
中声明权限:
<uses-permission android:name="android.permission.INTERNET" />
库名 | 特点 | 适用场景 |
---|---|---|
Retrofit | 简洁、支持多种数据格式(JSON/XML) | RESTful API请求 |
OkHttp | 轻量级、可扩展性强 | 基础网络请求 |
Volley | 适合小数据量、支持缓存 | 简单GET/POST请求 |
Step 1: 添加依赖
implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
Step 2: 定义API接口
public interface ApiService { @GET("getData.php") // 替换为实际API路径 Call<List<User>> getUsers(); }
Step 3: 创建数据模型
public class User { private int id; private String name; // Getter/Setter方法 }
Step 4: 发起请求
Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://yourserver.com/api/") // 替换为服务器地址 .addConverterFactory(GsonConverterFactory.create()) .build(); ApiService apiService = retrofit.create(ApiService.class); Call<List<User>> call = apiService.getUsers(); call.enqueue(new Callback<List<User>>() { @Override public void onResponse(Call<List<User>> call, Response<List<User>> response) { if (response.isSuccessful()) { List<User> users = response.body(); // 更新UI,例如RecyclerView适配器 } } @Override public void onFailure(Call<List<User>> call, Throwable t) { // 处理错误(如网络异常) } });
问题 | 原因 | 解决方案 |
---|---|---|
无法连接到服务器 | URL错误、网络权限未声明、服务器防火墙限制 | 检查URL拼写、确认INTERNET 权限、配置服务器允许外部访问 |
JSON解析失败 | 数据格式不匹配、字段命名不一致 | 使用工具(如Postman)验证API返回数据,确保模型类与JSON字段一致 |
主线程网络操作崩溃 | Android禁止在主线程执行网络请求 | 使用enqueue 异步请求或AsyncTask /Coroutine 处理 |
避免明文传输敏感数据
防止SQL注入
$stmt = $conn->prepare("SELECT FROM users WHERE id = ?"); $stmt->bind_param("i", $id); // $id为用户输入 $stmt->execute();
解答:
RecyclerView
布局并添加适配器。 onResponse
中将数据传递给适配器: MyAdapter adapter = new MyAdapter(users); // users为解析后的数据列表 recyclerView.setAdapter(adapter);
解答:
修改API接口定义,添加动态参数:
@GET("getData.php") Call<List<User>> getUsers(@Query("userId") int userId); // 通过?userId=xxx传递参数
调用时传入参数:
Call<List<User>> call = apiService.getUsers(123); // 传递userId=123