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": "登陆成功"
}
上一篇 OKHttp3学习之三:GET请求
下一篇 OKHttp3学习之五:POST请求(JSON参数形式)
目录
文章列表
1 设计模式(16)访问者模式
设计模式(16)访问者模式
2
Kubernetes api微服务开发之pod创建与删除
Kubernetes api微服务开发之pod创建与删除
3
Sharding-Sphere:Sharding-JDBC分库分表(基于JPA)
Sharding-Sphere:Sharding-JDBC分库分表(基于JPA)
4
高等数学基础:线性代数与矩阵
高等数学基础:线性代数与矩阵
5
BigDecimal精度scale设定
BigDecimal精度scale设定
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。