OKHttp3学习之三:GET请求

需求:实现用户信息获取并在UI界面上显示

在app模块的build.gradle配置

1
2
compile 'com.squareup.okhttp3:okhttp:3.4.2'
compile 'com.squareup.picasso:picasso:2.5.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
public void getRequest(View view) {
OkHttpClient client = new OkHttpClient();
String url = SERVER_ADDRESS + "/user/info?id=1";
Request request = new Request.Builder().url(url).get().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();

showUserInfo(result);
}
}
}
});
}

private void showUserInfo(final String result) {
//在主线程中实现UI更新
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
JSONObject json = new JSONObject(result);
String id = json.optString("id");
String username = json.optString("username");
String head_url = json.optString("head_url");
mTvNickName.setText(username);
//利用Picasso图片加载框架实现头像异步加载
Picasso.with(MainActivity.this).load(head_url).resize(100, 100).centerCrop().into(mIvAvatar);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}

服务器返回数据

1
2
3
4
5
{
"head_url": "http://www.appblog.cn/images/avatar.png",
"id": "1",
"username": "Joe.Ye"
}

Powered by AppBlog.CN     浙ICP备14037229号

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

访客数 : | 访问量 :