(注意:模拟器要联网,电脑要连接网络)
1.导入依赖包
在build.gradle.kts文件中导入
(可直接复制代码)
dependencies {
//okhttp
implementation("com.squareup.okhttp3:okhttp:4.11.0")
}
点击同步按钮(大象的图案)
2.添加网络权限
在文件AndroidManifest.xml中添加网络请求权限
文件位置如图:
(可直接复制代码)
<uses-permission android:name="android.permission.INTERNET" />
android:usesCleartextTraffic="true"
3.在java文件中编写代码
3.1 发送请求
get()方法 不带参数
post()方法 带参数
3.2解析结果数据
(可直接复制代码)
//1.发送请求
Request request = new Request.Builder()
.url("http://....")//服务器地址
.get()
.build();
OkHttpClient okHttpClient = new OkHttpClient();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {//加入请求队列
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
//请求失败
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
//请求成功
//2.解析数据
String result = response.body().string();//拿到请求的数据
Log.i("test",result);//打印结果
}
});
在Logcat(小猫的图案)可查看打印结果(可以在过滤器中筛选“test”),如图的绿色圈
post方法
在原来get的基础上添加即可
代码:
FormBody formBody = new FormBody.Builder()
.add("phonenumber",phonenumber)
.add("password",password)
.build();
Request request = new Request.Builder()
.url("https://....com")
.post(formBody)
.build();
注意ui控件的操作要放到主线程中如:
textView.setText(result);
1.如图onCreate方法里面的都是主线程
2.如何在在子线程内切换主线程?
如图
橙色框内的是子线程
红色框:主线程
代码:用runOnUiThread()方法
(可直接复制代码)
//切换到主线程
runOnUiThread(new Runnable() {
@Override
public void run() {
//主线程
}
});
例子1:解析JSON简单数据
后端数据:
添加位置如下:
代码:
//主线程
try {
JSONObject jsonObject = new JSONObject(result);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
textView.setText(name + age);
} catch (JSONException e) {
throw new RuntimeException(e);
}
例子2:解析嵌套数据对象
从外层到内层解析
后端数据:
添加代码位置如图:
代码:
//"class"
JSONObject jsonObject1 = jsonObject.getJSONObject("class");
String classname = jsonObject1.getString("classname");
例子3:JSON嵌套数组
后端数据:
添加代码的位置:
代码:
//"students"
JSONArray studentsJsonArray = jsonObject.getJSONArray("students");
for (int i = 0;i < studentsJsonArray.length();i++){
String students = (String) studentsJsonArray.get(i);
//强制转换字符串类型 打印
Log.i("test","i="+ students);