You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中使用Retrofit传递多个GET参数实现登录验证

使用Retrofit实现Android登录API调用(带URL参数)

看你已经在搭建Retrofit登录调用的基础了,我来帮你补全整个实现流程,确保能正确调用那个带参数的登录API:

1. 补全你的Utils类

先把你未完成的Utils类补全,这里我们把Retrofit实例的创建也整合进来,方便全局复用:

public class Utils {
    public static final String USER_TYPE = "1";
    public static final String DEVICE_ID = "12345";
    private static final String BASE_URL = "http://example.com/";
    
    // 创建全局唯一的Retrofit实例
    private static Retrofit getRetrofitInstance() {
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    
    // 对外提供ApiService实例
    public static ApiService getApiService() {
        return getRetrofitInstance().create(ApiService.class);
    }
}

2. 定义ApiService接口

接下来创建ApiService接口,用Retrofit的注解声明登录API的请求规则——因为你的请求是GET方式,参数直接拼接在URL里,所以用@GET指定相对路径,@Query传递参数:

public interface ApiService {
    // 登录接口:相对路径对应你完整URL里的"park/app/login.php"
    @GET("park/app/login.php")
    Call<LoginResponse> login(
            @Query("username") String username,
            @Query("password") String password,
            @Query("user_type") String userType,
            @Query("device_id") String deviceId
    );
}

补充:创建响应实体类

你需要定义LoginResponse类来解析服务器返回的JSON数据,示例如下(根据实际返回结构调整):

public class LoginResponse {
    private boolean success;
    private String message;
    private UserData data; // 服务器返回用户信息时用
    
    // 生成getter和setter方法
    public boolean isSuccess() { return success; }
    public void setSuccess(boolean success) { this.success = success; }
    public String getMessage() { return message; }
    public void setMessage(String message) { this.message = message; }
    public UserData getData() { return data; }
    public void setData(UserData data) { this.data = data; }
    
    // 内部类存储用户详情(按需添加)
    public static class UserData {
        private String userId;
        private String userName;
        
        public String getUserId() { return userId; }
        public void setUserId(String userId) { this.userId = userId; }
        public String getUserName() { return userName; }
        public void setUserName(String userName) { this.userName = userName; }
    }
}

3. 调用登录API

在Activity或ViewModel里发起异步请求(Retrofit的enqueue方法会自动在子线程执行网络操作):

// 示例:登录按钮点击事件
btnLogin.setOnClickListener(v -> {
    String username = etUsername.getText().toString().trim();
    String password = etPassword.getText().toString().trim();
    
    // 获取ApiService实例并发起请求
    ApiService apiService = Utils.getApiService();
    Call<LoginResponse> call = apiService.login(username, password, Utils.USER_TYPE, Utils.DEVICE_ID);
    
    call.enqueue(new Callback<LoginResponse>() {
        @Override
        public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
            if (response.isSuccessful() && response.body() != null) {
                LoginResponse loginResponse = response.body();
                if (loginResponse.isSuccess()) {
                    // 登录成功:跳转主页、保存用户信息等
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    UserData userData = loginResponse.getData();
                    if (userData != null) {
                        // 比如保存用户ID到SharedPreferences
                    }
                } else {
                    // 登录失败:显示服务器返回的错误信息
                    Toast.makeText(LoginActivity.this, loginResponse.getMessage(), Toast.LENGTH_SHORT).show();
                }
            } else {
                // 服务器返回错误状态码
                Toast.makeText(LoginActivity.this, "请求失败:" + response.code(), Toast.LENGTH_SHORT).show();
            }
        }
        
        @Override
        public void onFailure(Call<LoginResponse> call, Throwable t) {
            // 网络异常:无网络、连接超时等
            Toast.makeText(LoginActivity.this, "网络错误:" + t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
});

4. 必备配置

添加依赖

在Module级别的build.gradle中添加Retrofit及Gson转换器依赖:

dependencies {
    // Retrofit核心库
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    // Gson解析转换器
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}

网络权限

在AndroidManifest.xml中添加网络权限:

<uses-permission android:name="android.permission.INTERNET" />

小提示

  • 不要硬编码DEVICE_ID,可以通过Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID)获取真实设备ID(注意Android 10+的权限限制);
  • 密码建议加密后再传递,避免明文传输风险。

内容的提问来源于stack exchange,提问作者chand mohd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:25:41