经过上一节介绍用自己搭建的springboot服务器请求阿里云对象存储服务器获取凭证,返回json凭证结果。这一节介绍在安卓开发中如何使用该凭证经行上传到阿里云对象存储中。
一、了解原理
这节中介绍完成图中的五六点。从图中可以知道要上传文件到oss,需要STS凭证。这个凭证的话就需要从后端服务器获取。这里涉及到网络解析json数据,我在这里简单介绍下采用retrofit2,okhttp3,Rxjava2三者结合实现。实现STS凭证上传用阿里云SDK中的asyncPutObject,待会在项目中会详细介绍。
二、环境配置
这里我采用kotlin实现Android开发,开发环境Android studio3.0。
首先对于环境配置来说对大家都不陌生了。
compile 'com.aliyun.dpa:oss-android-sdk:2.4.5'
compile 'io.reactivex.rxjava2:rxjava:2.1.8'
compile 'com.squareup.okhttp3:okhttp: 3.4.1'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
三、代码详解
封装retrofit工厂
import com.ckkj.zct.baselibrary.commen.BaseConstant
import com.ckkj.zct.baselibrary.utils.AppPrefsUtils
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
/**
* @author zct
* Created by zct11 on 2018/1/19.
* Retrofit工厂,单例
*/
class RetrofitFactory private constructor(){
/*
单例实现
*/
companion object {
val instance:RetrofitFactory by lazy { RetrofitFactory() }
}
private val interceptor:Interceptor
private val retrofit:Retrofit
//初始化
init {
//通用拦截
interceptor = Interceptor {
chain -> val request = chain.request()
.newBuilder()
.addHeader("Content_Type","application/json")
.addHeader("charset","UTF-8")
.addHeader("token", AppPrefsUtils.getString(BaseConstant.KEY_SP_TOKEN))
.build()
chain.proceed(request)
}
//Retrofit实例化
retrofit = Retrofit.Builder()
.baseUrl(BaseConstant.SERVER_ADDRESS)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(initClient())
.build()
}
/*
OKHttp创建
*/
private fun initClient():OkHttpClient{
return OkHttpClient.Builder()
.addInterceptor(initLogInterceptor())
.addInterceptor(interceptor)
.connectTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.build()
}
/*
日志拦截器
*/
private fun initLogInterceptor():HttpLoggingInterceptor{
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
return interceptor
}
/*
具体服务实例化
*/
fun <T> create(serv