OKHttp3学习之四:POST请求(Form表单形式)

需求:实现用户登陆,登录信息以Form表单数据的形式发送

在app模块的build.gradle配置

compile 'com.squareup.okhttp3:okhttp:3.4.2'

实现源码

public void postRequest(View view) {
    String username = mEtUserName.getText().toString().trim();
    String password = mEtPassWord.getText().toString().trim();
    loginWithForm(username, password);
}

private void loginWithForm(String username, String password) {
    OkHttpClient client = new OkHttpClient();
    String url = SERVER_ADDRESS + "/login";
    //设置Form表单数据
    RequestBody body = new FormBody.Builder()
            .add("username", username)
            .add("password", password)
            .build();
    Request request = new Request.Builder().url(url).post(body).build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.i(TAG, "请求失败: " + e.getLocalizedMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                ResponseBody body = response.body();
                if (body != null) {
                    String result = body.string();
                    Log.i(TAG, "返回成功: " + result);
                    body.close();

                    JSONObject json = null;
                    try {
                        json = new JSONObject(result);
                        final int code = json.optInt("code");
                        final String message = json.optString("message");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (code == 1) {
                                    Log.i(TAG, "登录成功");
                                } else {
                                    Log.i(TAG, "登录失败");
                                }
                                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    });
}

服务器返回数据

{
    "code": 1,
    "message": "登陆成功"
}

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/02/25/okhttp3-learning-4-post-request-form/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
OKHttp3学习之四:POST请求(Form表单形式)
需求:实现用户登陆,登录信息以Form表单数据的形式发送 在app模块的build.gradle配置 compile 'com.squareup.okhttp3:okhttp:3.4.2' 实现源码 pub……
<<上一篇
下一篇>>
文章目录
关闭
目 录