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

Android登录页如何将用户名密码以JSON格式POST到服务器?

问题分析与解决建议

你的代码里存在几个关键问题导致无法向服务器提交正确数据:

1. 输入内容获取时机错误

你在onCreate初始化阶段就调用getText().toString()获取输入框内容,此时用户还未在输入框中输入任何信息,etUsername和etPassword保存的是输入框的初始空值,点击提交时发送的自然是空数据。

2. 请求URL为空

Request.Builder()中的.url("")未填写实际服务器接口地址,请求无法正确发送到目标服务器。

3. 冗余代码与资源浪费

  • 重复创建OkHttpClient实例:onCreate和点击事件中各创建一个,没必要,复用单个实例即可。
  • 未完成的AlertDialog代码:仅初始化了Builder但无后续构建逻辑,属于无效冗余代码。

修正后的代码示例

public class MainActivity extends AppCompatActivity {

    EditText etUsername;
    EditText etPassword;
    Button btSubmit;
    TextView textViewResult;
    // 复用OkHttpClient实例
    OkHttpClient client = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 只初始化控件引用,不获取文本内容
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        btSubmit = findViewById(R.id.bt_submit);
        textViewResult = findViewById(R.id.text_view_result);

        btSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击提交时才获取当前输入框的内容
                String username = etUsername.getText().toString().trim();
                String password = etPassword.getText().toString().trim();

                // 可选:添加输入非空验证
                if (username.isEmpty() || password.isEmpty()) {
                    textViewResult.setText("用户名或密码不能为空");
                    return;
                }

                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("app_id", "123");
                    jsonObject.put("username", username);
                    jsonObject.put("password", password);
                    jsonObject.put("firebase_token", "123");
                } catch (JSONException e) {
                    e.printStackTrace();
                    textViewResult.setText("数据格式错误");
                    return;
                }

                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                RequestBody body = RequestBody.create(JSON, jsonObject.toString());
                // 替换为实际的服务器登录接口地址
                Request request = new Request.Builder()
                        .url("https://your-server-domain/api/login")
                        .post(body)
                        .build();

                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        runOnUiThread(() -> textViewResult.setText("请求失败:" + e.getMessage()));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (response.isSuccessful()) {
                            String myResponse = response.body().string();
                            runOnUiThread(() -> textViewResult.setText(myResponse));
                        } else {
                            runOnUiThread(() -> textViewResult.setText("请求失败:" + response.code()));
                        }
                    }
                });
            }
        });
    }
}

额外注意事项

  • 确保AndroidManifest.xml中添加了网络权限:
    <uses-permission android:name="android.permission.INTERNET"/>
    
  • 针对Android 9及以上版本,如果使用HTTP接口,需要在AndroidManifest.xml的<application>标签中添加android:usesCleartextTraffic="true",或者改用HTTPS接口。
  • 可以添加更多输入验证逻辑,比如密码长度校验、用户名格式校验等,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:25:53