Retrofit+Gson解析工具类封装
定义Retrofit Service类
import android.os.Build
import cn.wtyc.weiwogroup.global.Constant
import cn.wtyc.weiwogroup.global.MyApplication
import cn.wtyc.weiwogroup.mvvm.utils.logV
import com.google.gson.GsonBuilder
import okhttp3.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.io.IOException
import java.util.Date
/**
* 网络基础服务配置。
* @author ym6745476
* @since 2021/10/14
*/
object RetrofitService {
const val BASE_URL = "https://127.0.0.1/"
val httpClient: OkHttpClient = OkHttpClient.Builder()
.addInterceptor(LoggingInterceptor())
.addInterceptor(HeaderInterceptor())
.addInterceptor(BasicParamsInterceptor())
.build()
private val builder = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(httpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().registerTypeAdapterFactory(
GsonTypeAdapterFactory()
).create()))
private val retrofit = builder.build()
fun <T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass)
class LoggingInterceptor : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val t1 = System.nanoTime()
//logV(TAG, "发送请求: ${request.method()} ${request.url()} ${request.headers()}")
logV(
TAG,String.format("发送请求 %s on %s%n%s",
request.url(), request.method(), request.headers()));
val response = chain.proceed(request)
val t2 = System.nanoTime()
//logV(TAG, "Received response for ${response.request().url()} in ${(t2 - t1) / 1e6} ms\n${response.headers()}")
val responseBody: ResponseBody = response.peekBody((1024 * 1024).toLong())
logV(
TAG,
String.format(
"接收响应: [%s] %n返回json:【%s】 %.1fms%n%s",
response.request().url(),
responseBody.string(),
(t2 - t1) / 1e6,
response.headers()
)
)
return response
}
companion object {
const val TAG = "LoggingInterceptor"
}
}
class HeaderInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val original = chain.request()
val request = original.newBuilder().apply {
header("model", "Android")
header("If-Modified-Since", "${Date()}")
header("User-Agent", System.getProperty("http.agent") ?: "unknown")
header("token", "传入你的token")
}.build()
return chain.proceed(request)
}
}
class BasicParamsInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val originalHttpUrl = originalRequest.url()
val url = originalHttpUrl.newBuilder().apply {
addQueryParameter("version", "${Build.VERSION.SDK_INT}")
}.build()
val request = originalRequest.newBuilder().url(url).method(originalRequest.method(), originalRequest.body()).build()
return chain.proceed(request)
}
}
}
定义TypeAdapterFactory
/**
* Gson解析
* @author ym6745476
* @since 2021/10/14
*/
class GsonTypeAdapterFactory : TypeAdapterFactory {
override fun <T : Any?> create(gson: Gson?, type: TypeToken<T>?): TypeAdapter<T> {
val adapter = gson?.getDelegateAdapter(this, type)
return object : TypeAdapter<T>() {
@Throws(IOException::class)
override fun write(out: JsonWriter?, value: T) {
adapter?.write(out, value)
}
@Throws(IOException::class)
override fun read(jr: JsonReader): T? {
return try {
adapter?.read(jr)
} catch (e: Throwable) {
e.printStackTrace()
consumeAll(jr)
null
}
}
@Throws(IOException::class)
private fun consumeAll(jr: JsonReader) {
if (jr.hasNext()) {
val peek: JsonToken = jr.peek()
when {
peek === JsonToken.STRING -> {
jr.nextString()
}
peek === JsonToken.BEGIN_ARRAY -> {
jr.beginArray()
consumeAll(jr)
jr.endArray()
}
peek === JsonToken.BEGIN_OBJECT -> {
jr.beginObject()
consumeAll(jr)
jr.endObject()
}
peek === JsonToken.END_ARRAY -> {
jr.endArray()
}
peek === JsonToken.END_OBJECT -> {
jr.endObject()
}
peek === JsonToken.NUMBER -> {
jr.nextString()
}
peek === JsonToken.BOOLEAN -> {
jr.nextBoolean()
}
peek === JsonToken.NAME -> {
jr.nextName()
consumeAll(jr)
}
peek === JsonToken.NULL -> {
jr.nextNull()
}
}
}
}
}
}
}
定义Service
interface RecordService { @GET("/api/list") suspend fun list(@Query("page") page:Int,@Query("pageSize") pageSize:Int): ServiceResult<RecordItem>
}
在Repository中定义
private var service = RetrofitService.create(RecordService:class.java)
suspend fun getList(size: Int): ServiceResult<RecordItem> {
return service.list(size)
}
配置Retrofit Get方式
@GET("/api/list")
suspend fun list(@Query("page") page:Int,@Query("pageSize") pageSize:Int): ServiceResult<RecordItem>
配置Retrofit Post Form方式
@FormUrlEncoded
@POST("/api/list")
suspend fun list(@Field("name") name:String): ServiceResult<RecordItem>
配置Retrofit Post Json方式
@Headers("Content-Type: application/json", "Accept: */*")
@POST("api/login")
suspend fun login(@Body data: RequestBody): ServiceResult<LoginUser>
var data = HashMap<String,String>()
data.put("mobile",mobile)
data.put("password",password)
val paramBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),Gson().toJson(data))
val response = userService.login(paramBody)
以上。
本站内容来源于作者发布和网络转载,如有版权相关问题请及时与我们取得联系,我们将立即删除。