一、Kotlin版本的retrofit+rxjava
简介
重磅来袭,关于什么是retrofit+rxjava,是做什么的,有什么优势,还有应该怎么学习,这里我就不多说,不懂的你们先去搜索有关资料,这里只介绍怎么使用和封装
废话不多说,来点你们最想要的代码:
代码
依赖:
implementation ‘com.squareup.retrofit2:retrofit:2.5.0’
implementation ‘com.squareup.retrofit2:converter-gson:2.5.0’
implementation ‘com.squareup.retrofit2:adapter-rxjava2:2.4.0’
implementation ‘io.reactivex.rxjava2:rxjava:2.2.0’
implementation ‘io.reactivex.rxjava2:rxandroid:2.1.0’
implementation ‘com.squareup.okhttp3:logging-interceptor:3.9.0’
可上线项目用的代码(retrofit+java结合MVVM使用)为:
【特别推荐】retrofit+java的代码下载
下面来一个简单的封装retrofit
1、data数据类
data class TokenData(
val access_token: String,
val token_type: String,
val refresh_token: String,
val expires_in: String,
val scope: String
)
2、retrofit工具类
class RetrofitUtil {
companion object {
const val TAG="RetrofitUtil"
/**
* 创建Retrofit
*/
fun create(url: String): Retrofit {
//显示日志级别
val level: HttpLoggingInterceptor.Level = HttpLoggingInterceptor.Level.BODY
//新建log拦截器
val loggingInterceptor: HttpLoggingInterceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message ->
Log.e(TAG,"OkHttp:$message")
})
loggingInterceptor.level = level
//okHttpClientBuilder
val okHttpClientBuilder = OkHttpClient.Builder()
okHttpClientBuilder.connectTimeout(60, TimeUnit.SECONDS)
okHttpClientBuilder.readTimeout(10, TimeUnit.SECONDS)
//OkHttp进行添加拦截器loggingInterceptor
okHttpClientBuilder.addInterceptor(loggingInterceptor)
return Retrofit.Builder()
.baseUrl(url)
.client(okHttpClientBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}
/**
* 获取ServiceApi
*/
fun <T> getService(url: String, service: Class<T>): T {
return create(url).create(service)
}
val retrofitService: RetrofitService = RetrofitUtil.getService(Constants.REQUEST_BASE_URL, RetrofitService::class.java)
}
}
3、api接口
interface RetrofitService {
@FormUrlEncoded //post的请求必须的
@Headers( "Content-Type:application/x-www-form-urlencoded; charset=UTF-8","Authorization:Basic YXBwOmZzbGg4ODQ4") //这里是请求头
@POST("authentication/form")
fun getToken(
@Field("grant_type") grant_type: String,
@Field("username") username: String,
@Field("password") password: String,
@Field("scope") scope: String
): Observable<TokenData>
}
4、最后在activity里面调用
val disposable1 = RetrofitUtil
.getService(Constants.TOKEN_BASE_URL, RetrofitService::class.java)
.getToken("password", "zhangqiang","123456","app")//2020-3-18日期
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ result ->
Log.i(TAG, "==json结果为:"+result.toString())
}, { error ->
Log.e(TAG, "==错误:"+error.message.toString())
})
二、volley的封装以及使用
- 添加网络
<uses-permission android:name="android.permission.INTERNET"/>
- 首先导入依赖:
implementation 'com.mcxiaoke.volley:library:1.0.+'
VolleyUtil
import android.content.Context
import android.util.Log
import com.android.volley.AuthFailureError
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import java.util.*
object VolleyUtil {
/**
* 通用的get访问
* 注意:请求返回的结果是json,如果是xml类型,需要JsonObjectRequest改成StringRequest
*/
open fun volleyGet(context: Context, JSONDataUrl: String, mListen: (String) -> Unit) {
val requestQueue = Volley.newRequestQueue(context)
//jsonObject:需要传递的数据,如果是以get方式传递,则为null,如果是以post方式传递,则需要设置数据。
val jsonObjectRequest = JsonObjectRequest(JSONDataUrl, null,
Response.Listener {
//请求成功
mListen(it.toString())
},
Response.ErrorListener { arg0 -> Log.i("WY+", "错误error=$arg0") })
requestQueue.add(jsonObjectRequest)
}
/**
* 通用volley (post请求)
* @param context
* @param url
* @param map
*/
fun volleyPost(
context: Context,
url: String,
map: Map<String, String>,
mListen: (String) -> Unit
) {
val requestQueue = Volley.newRequestQueue(context)
val request = object : StringRequest(Method.POST, url, Response.Listener { s ->
Log.i("WY+", "=服务器返回的结果(volleypost)=$s")
mListen(s)
}, Response.ErrorListener { volleyError ->
Log.e("WY+", "=服务器访问出错(volleypost)=$volleyError")
}) {
//请求form表单
@Throws(AuthFailureError::class)
public override fun getParams(): Map<String, String> {
//这里直接返回传进来的map,也可以修改成其他的map或者添加元素
return map
}
//请求头和Authorization
@Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers = HashMap<String, String>()
headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8"
headers["Authorization"] = "Basic YXBwOmZzbGg4ODQ4"
return headers
}
}
request.tag = "volleypost"
requestQueue.add(request)
}
/**
* 通用volley (post请求),请求头可变
*
* @param context
* @param url
* @param map
*/
fun volleyPost_2(
context: Context,
url: String,
formMap: Map<String, String>,
headerMap: Map<String, String>,
mListen: (String) -> Unit
) {
val requestQueue = Volley.newRequestQueue(context)
val request = object : StringRequest(Request.Method.POST, url, Response.Listener { s ->
Log.i("WY+", "=服务器返回的结果(volleypost)=$s")
mListen(s)
}, Response.ErrorListener { volleyError ->
Log.e("WY+", "=服务器访问出错(volleypost)=$volleyError")
}) {
//请求form表单
@Throws(AuthFailureError::class)
public override fun getParams(): Map<String, String> {
//这里直接返回传进来的map,也可以修改成其他的map或者添加元素
return formMap
}
//请求头和Authorization
@Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
// val headers = HashMap<String, String>()
// headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8"
// headers["Authorization"] = "Basic YXBwOmZzbGg4ODQ4"
// return headers
return headerMap
}
}
request.tag = "volleypost"
requestQueue.add(request)
}
}
使用
VolleyUtil.volleyGet(content,"你自己的url"){
Log.d("WY+","请求结果为:"+it)
}
三、retrofit+协程的封装
使用到flow流的封装处理异常结果,比较推荐使用,本人项目中也在使用,暂未发现问题
下载地址:https://download.csdn.net/download/wy313622821/87248436
四、retrofit+协程的封装(优雅的使用flow来处理loading)
上面的代码没有加入loading的处理:开始请求loading,结束请求取消loading,如果需要则使用如下的代码:
下载地址:https://download.csdn.net/download/wy313622821/87250395
五、完整版retrofit+协程的封装(异常状态码的处理,优雅的使用flow来处理loading,无缝刷新token)
下载地址:https://download.csdn.net/download/wy313622821/87251316