Android中封装OkHttp,处理网络请求
Android中常用的组合是OkHttp+Retrofit。
OKHttp
- 添加权限
<uses-permission android:name="android.permission.INTERNET" />
- 添加依赖
//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
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
//自动释放RxJava相关资源
//https://github.com/uber/AutoDispose
implementation "com.uber.autodispose2:autodispose-androidx-lifecycle:2.1.1"
- 添加全局配置
android {
//配置不同的环境
productFlavors {
//本地开发环境
local {
//API端点
buildConfigField('String', "ENDPOINT", '"http://192.168.2.108:8080/"')
//资源端点
buildConfigField 'String', 'RESOURCE_ENDPOINT', '"http://course-music-dev.ixuea.com/%s"'
dimension = minSdkVersion
buildFeatures{
buildConfig = true
}
}
//开发环境
dev {
//API端点
buildConfigField('String', "ENDPOINT", '"http://my-cloud-music-api-sp3-dev.ixuea.com/"')
//资源端点
buildConfigField 'String', 'RESOURCE_ENDPOINT', '"http://course-music-dev.ixuea.com/%s"'
dimension = minSdkVersion
buildFeatures{
buildConfig = true
}
}
//正式环境
prod {
//API端点
buildConfigField 'String', 'ENDPOINT', '"http://my-cloud-music-api-sp3.ixuea.com/"'
//资源端点
buildConfigField 'String', 'RESOURCE_ENDPOINT', '"http://course-music.ixuea.com/%s"'
dimension = minSdkVersion
buildFeatures{
buildConfig = true
}
}
}
}
- 创建配置文件
package com.ixuea.courses.mymusic.config;
import com.ixuea.courses.mymusic.BuildConfig;
/**
* 配置文件
* <p>
* 例如:API地址,QQ等第三方服务配置信息等
*/
public class Config {
/**
* 默认延时时间
*/
public static final long SPLASH_DEFAULT_DELAY_TIME = 1500;
/**
* 是否是调试模式
*/
public static final boolean DEBUG = BuildConfig.DEBUG;
/**
* 端点
*/
public static String ENDPOINT = BuildConfig.ENDPOINT;
/**
* 资源端点
*/
public static String RESOURCE_ENDPOINT = BuildConfig.RESOURCE_ENDPOINT;
/**
* 网络缓存目录大小
* 100M
*/
public static final long NETWORK_CACHE_SIZE = 1024 * 1024 * 100;
}
- 使用OkHttp请求网络
private void testGet() {
OkHttpClient client = new OkHttpClient();
String url = Config.ENDPOINT + "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.getLocaliz