//網(wǎng)絡(luò)請求牛隅,基本配置
import android.util.Log
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
object RetrofitUtil {
val CONNECT_TIME_OUT = 200
val READ_TIME_OUT = 200
val WRITE_TIME_OUT = 200
var loggingInterceptor =
HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message -> Log.i("retrofitBack = " , message) })
fun getRetrofit(): Retrofit {
val commonParamsInterceptor = CommonParamsInterceptor()
//打印retrofit日志
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(commonParamsInterceptor)
.addInterceptor(loggingInterceptor)
.connectTimeout(CONNECT_TIME_OUT.toLong(), TimeUnit.SECONDS)
.readTimeout(READ_TIME_OUT.toLong(), TimeUnit.SECONDS)
.writeTimeout(WRITE_TIME_OUT.toLong(), TimeUnit.SECONDS)
.build()
val retrofit = Retrofit.Builder()
.baseUrl("自己公司baseUrl")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build();
return retrofit;
}
fun <T> create(service: Class<T>): T {
return getRetrofit().create(service)
}
}
object HttpRxObservable {
fun <T> getObservable(apiObservable: Observable<HttpResult<T>>): Observable<*> {
return apiObservable
.observeOn(AndroidSchedulers.mainThread())
.map(ResultFunction<T>()) //返回數(shù)據(jù)的處理
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.onExceptionResumeNext{HttpResultFunction<T>()} //失敗數(shù)據(jù)的處理
}
}
abstract class HttpRxObserver<T> : Observer<T>, HttpRequestListener {
override fun onError(e: Throwable) {
if (e is ApiException) {
onError(e)
} else {
onError(ApiException(e, ExceptionEngine.UN_KNOWN_ERROR))
}
}
override fun onComplete() {}
override fun onNext(@NonNull t: T) {
onSuccess(t)
}
override fun onSubscribe(@NonNull d: Disposable) {
onStart(d)
}
override fun cancel() {
}
protected abstract fun onStart(d: Disposable)
protected abstract fun onError(e: ApiException)
protected abstract fun onSuccess(response: T)
}
interface HttpRequestListener {
fun cancel()
}
//攔截器以及公用參數(shù)的處理
class CommonParamsInterceptor : Interceptor {
val TYPE_JSON: MediaType = MediaType.parse("application/json; charset=utf-8")!!
override fun intercept(chain: Interceptor.Chain?): Response {
val request: Request = chain!!.request()
val builder: Request.Builder = request.newBuilder();
val token = ""
val version = "1.0.0"
builder.addHeader("device-typ", "3")
builder.addHeader("channel-id", "")
builder.addHeader("version", version)
builder.addHeader("token", token)
return chain.proceed(methodPost(request, builder))
}
fun methodPost(request: Request, builder: Request.Builder): Request {
val jsonObject = JSONObject()
var requestBody = request.body()
//有好幾種body
when (requestBody) {
is FormBody -> {
val oldBody = request.body() as FormBody?
for (i in 0 until oldBody!!.size()) {
jsonObject.put(oldBody.encodedName(i), oldBody.encodedValue(i))
}
requestBody = RequestBody.create(TYPE_JSON, JSONObject.toJSONString(jsonObject))
}
}
return builder.post(requestBody).build()
}
}
class ServerException(val code: Int, val msg: String) : RuntimeException()
class ResultFunction<T> : io.reactivex.functions.Function<HttpResult<T>, T>{
override fun apply(httpResult: HttpResult<T>): T {
if(!httpResult.isSuccess){
throw ServerException(httpResult.errcode, httpResult.errmsg)
}
return httpResult.data!!
}
}
class HttpResultFunction<T> : Function<Throwable, Observable<T>> {
@Throws(Exception::class)
override fun apply(@NonNull throwable: Throwable): Observable<T> {
//打印具體錯誤
return Observable.error(ExceptionEngine.handleException(throwable))
}
}
object ExceptionEngine {
val UN_KNOWN_ERROR = 1000//未知錯誤
fun handleException(e: Throwable): ApiException {
val ex: ApiException
if (e is HttpException) { //HTTP錯誤
ex = ApiException(e, e.code())
return ex
} else if (e is ServerException) { //服務(wù)器返回的錯誤
ex = ApiException(e.code,e.msg)
return ex
} else { //未知錯誤
ex = ApiException(e, UN_KNOWN_ERROR)
return ex
}
}
}
//返回值的統(tǒng)一處理基類
class HttpResult<T> {
var errcode: Int = 0
var errmsg: String = ""
var data: T? = null
val isSuccess: Boolean
get() = if (errcode == 0) true else false
}
interface MainService {
@JvmSuppressWildcards
@POST("自己公司的url地址")
fun getTodoList(@Body map: Map<String, Any>): Observable<HttpResult<TodoListBean>>
}
//測試類
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import com.chengan.study.testkotlin.main.TodoListBean
import com.chengan.study.testkotlin.network.*
import io.reactivex.disposables.Disposable
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getTodoList()
}
fun getTodoList(){
val hashMap = hashMapOf<String, Any>(
"page_size" to 50,
"page_num" to 1
)
val httpRxObserver = TodoRxObserver()
val observable = HttpRxObservable.getObservable(RetrofitUtil.create(MainService::class.java).getTodoList(hashMap))
observable.subscribe { httpRxObserver }
}
class TodoRxObserver : HttpRxObserver<TodoListBean>() {
override fun onStart(d: Disposable) {
}
override fun onError(e: ApiException) {
Log.i("",e.message)
}
override fun onSuccess(response: TodoListBean) {
Log.i("",response.data_list!![0].object_name)
}
}
}
如果有些庫在使用的時候發(fā)現(xiàn)不好用竭翠,請不要懷疑,就是不兼容O笞骸J呓!