添加权限
网络权限只需要写在清单文件中,不需要动态获取权限
<uses-permission android:name="android.permission.INTERNET" />
网络框架
Android中常用的组合是OkHttp+Retrofit。
添加依赖
//region 请求网络相关
//提示:region这种语法是最新的,推荐使用这种,也更容易阅读,不建议在同一个文件同时使用
//因为可能会显示出错
//okhttp
//https://github.com/square/okhttp
implementation 'com.squareup.okhttp3:okhttp:4.9.3'
//用来打印okhttp请求日志
//当然也可以自定义
implementation("com.squareup.okhttp3:logging-interceptor:4.9.3")
//retrofit
//https://github.com/square/retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
//使用gson解析json
//https://github.com/google/gson
implementation 'com.google.code.gson:gson:2.9.0'
//适配retrofit使用gson解析
//版本要和retrofit一样
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
//适配retrofit支持rxjava,可以解决异步回调地狱问题;网络请求,数据库请求返回rxjava对象统一处理
implementation 'com.squareup.retrofit2:adapter-rxjava3:2.9.0'
//使用了Android响应式编程
//RxJava和RxAndroid区别?
//简单来说:就是RxAndroid在RxJava的基础上
//优化了一些功能
//增强了Android特有的功能
//https://github.com/ReactiveX/RxAndroid
implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
//endregion
使用OkHttp请求网络
private void testGet() {
OkHttpClient client = new OkHttpClient();
String url = "http://test.com/v1/songs";
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
Log.e(TAG, "onFailure: "+e.getLocalizedMessage());
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
Log.d(TAG, "onResponse: "+response.body().string());
}
});
}
配置网络策略
请求http会失败,需要配置网络策略
1. 新建 xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<!--禁用掉明文流量请求的检查-->
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
2. 清单文件配置
<application
...
android:networkSecurityConfig="@xml/network_security_config">
1
1
1
1
1
1
1
1
1
1