
本文讲解在 retrofit 中发起 post 请求时,如何让请求体(如用户注册信息)与响应体(如返回的 id 和 token)使用不同数据结构,实现灵活、类型安全的网络通信。
本文讲解在 retrofit 中发起 post 请求时,如何让请求体(如用户注册信息)与响应体(如返回的 id 和 token)使用不同数据结构,实现灵活、类型安全的网络通信。
在 Android 开发中,使用 Retrofit 发起网络请求时,一个常见且关键的设计原则是:请求数据结构(Request)与响应数据结构(Response)应解耦、独立建模。以用户注册场景为例——客户端需提交 firstName、lastName、age、phone、password 等字段,而服务端返回的却是 id(long 类型)和 token(String 类型)。二者字段语义、数量、类型均不一致,绝不可共用同一实体类。
✅ 正确做法是分别定义两个 POJO 类:
// 请求体:封装要发送的用户注册数据
public class RegisterRequest {
private String firstName;
private String lastName;
private int age;
private String phone;
private String password;
// 必须提供无参构造函数(Gson/Retrofit 反序列化所需)
public RegisterRequest() {}
public RegisterRequest(String firstName, String lastName, int age, String phone, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.phone = phone;
this.password = password;
}
// getter / setter 省略(实际开发中请完整补充)
}
// 响应体:仅映射服务端返回的字段
public class RegisterResponse {
private long id;
private String token;
public RegisterResponse() {} // 同样需要无参构造
// getter / setter(推荐使用 IDE 自动生成)
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public String getToken() { return token; }
public void setToken(String token) { this.token = token; }
}
接着,在 Retrofit 接口定义中,使用 @POST 注解声明方法,并通过 @Body 传递请求对象(推荐 JSON Body 方式,更符合 REST 规范),而非分散的 @Query 参数(后者适用于简单 GET 查询,不适用于含敏感字段如密码的 POST):
public interface ApiService {
@POST("api/v1/register")
Call<registerresponse> registerUser(@Body RegisterRequest request);
}</registerresponse>
⚠️ 注意事项:
- 确保已配置 GsonConverterFactory(或你选用的序列化器)到 Retrofit.Builder 中;
- RegisterRequest 字段名需与服务端期望的 JSON key 严格一致(可配合 @SerializedName("first_name") 适配下划线命名);
- 敏感字段(如 password)禁止使用 @Query 明文拼接 URL,必须走 @Body + HTTPS 加密传输;
- 实际调用时务必在主线程外执行(如配合 enqueue() 异步回调,或 CoroutineCallAdapterFactory 使用协程)。
总结:Retrofit 的核心优势之一正是其类型安全的请求/响应解耦能力。通过分离 @Body 请求类与 Call










