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

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

在app模块的build.gradle配置

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

实现源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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();
}
}
}
}
});
}

服务器返回数据

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

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :