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

Retrofit 2:如何使用Base64编码密码进行POST请求?

搞定Retrofit 2的登录请求:带Base64编码密码的RequestBody实现

嘿,我来帮你把这个登录请求搞定!你已经有了Retrofit的接口定义和密码编码的雏形,接下来只需要把这些部分组装起来就行,我分两种常见的方式给你说明:

方式一:手动构建JSON请求体(无需额外数据类)

这种方式适合不想新增实体类的场景,直接用JSONObject来拼装参数:

  1. 补全密码的Base64编码
    记得指定UTF-8字符集避免乱码,同时用NO_WRAP参数去掉Base64字符串里的换行符(很多后端不接受带换行的编码结果):

    import android.util.Base64;
    import java.nio.charset.StandardCharsets;
    
    // 假设email和password是传入仓库类的参数
    String encodedPassword = Base64.encodeToString(
        password.getBytes(StandardCharsets.UTF_8),
        Base64.NO_WRAP
    );
    
  2. 构建JSON请求体并转为RequestBody
    把邮箱和编码后的密码塞进JSON,再转成Retrofit需要的RequestBody:

    import org.json.JSONObject;
    import org.json.JSONException;
    import okhttp3.RequestBody;
    import okhttp3.MediaType;
    
    // 拼装JSON参数
    JSONObject payloadJson = new JSONObject();
    try {
        payloadJson.put("email", email);
        payloadJson.put("password", encodedPassword);
    } catch (JSONException e) {
        e.printStackTrace();
        // 这里可以根据业务需求处理异常,比如返回错误回调或者抛出自定义异常
    }
    
    // 转为RequestBody
    RequestBody requestBody = RequestBody.create(
        payloadJson.toString(),
        MediaType.parse("application/json; charset=utf-8")
    );
    
  3. 调用Retrofit接口并执行请求
    拿到RequestBody后就可以调用你的接口了,记得处理异步回调:

    Call<String> loginCall = yourRetrofitApi.login(requestBody);
    loginCall.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            if (response.isSuccessful()) {
                // 登录成功,处理返回的字符串结果
                String loginResult = response.body();
            } else {
                // 处理接口返回的错误,比如401、404等
                String errorBody = response.errorBody() != null ? response.errorBody().string() : "未知错误";
            }
        }
    
        @Override
        public void onFailure(Call<String> call, Throwable t) {
            // 处理网络失败,比如无网络、超时等
            t.printStackTrace();
        }
    });
    

方式二:用数据类+Gson转换器(更简洁推荐)

如果你的项目已经引入了Gson转换器,这种方式更优雅,代码可读性更高:

  1. 创建登录请求数据类
    定义一个实体类来对应请求参数:

    public class LoginRequest {
        private String email;
        private String password;
    
        // 构造方法
        public LoginRequest(String email, String encodedPassword) {
            this.email = email;
            this.password = encodedPassword;
        }
    
        // 可选:如果需要自定义JSON键名,可以用@SerializedName注解
        // 比如@SerializedName("user_email") private String email;
    }
    
  2. 确保Retrofit配置了Gson转换器
    你的Retrofit实例需要添加GsonConverterFactory,不然无法自动转对象为JSON:

    import retrofit2.Retrofit;
    import retrofit2.converter.gson.GsonConverterFactory;
    
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("你的接口基础URL")
        .addConverterFactory(GsonConverterFactory.create())
        .build();
    
  3. 组装请求体并调用接口
    可以直接把数据类转为RequestBody,甚至可以修改你的Retrofit接口来直接接受LoginRequest对象(更省事):

    // 先编码密码
    String encodedPassword = Base64.encodeToString(
        password.getBytes(StandardCharsets.UTF_8),
        Base64.NO_WRAP
    );
    
    // 方式A:继续用原来的RequestBody接口
    LoginRequest loginRequest = new LoginRequest(email, encodedPassword);
    RequestBody requestBody = RequestBody.create(
        new Gson().toJson(loginRequest),
        MediaType.parse("application/json; charset=utf-8")
    );
    Call<String> loginCall = yourRetrofitApi.login(requestBody);
    
    // 方式B:修改接口定义,直接接受LoginRequest(推荐)
    // 把原来的接口改成:
    // @POST("login") Call<String> login(@Body LoginRequest loginRequest);
    // 这样就不用手动转RequestBody了,Retrofit会自动处理:
    // Call<String> loginCall = yourRetrofitApi.login(new LoginRequest(email, encodedPassword));
    

特殊情况:如果接口是表单格式(application/x-www-form-urlencoded)

要是你的后端期望表单格式而非JSON,那用FormBody来构建就行:

import okhttp3.FormBody;

FormBody formBody = new FormBody.Builder()
    .add("email", email)
    .add("password", encodedPassword)
    .build();
Call<String> loginCall = yourRetrofitApi.login(formBody);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:21:29