(var code: Int?, var msg: String?, val data: T?) :
14 | IResponseModel {
15 |
16 | override fun isSuccessful() = code == 0
17 |
18 | override fun toString(): String {
19 | return "DefaultResponseModel(code=$code, msg=$msg, data=$data)"
20 | }
21 | }
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/cipher/DefaultCipher.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.cipher
2 |
3 | /**
4 | * 默认的加解密器
5 | *
6 | * 示例实现
7 | * * 在[encrypt]中实现加密逻辑
8 | * * 在[decrypt]中实现解密逻辑
9 | * * [getParamName]配置与服务端协商好的加密字段key
10 | * @author: FreddyChen
11 | * @date : 2022/01/13 16:11
12 | * @email : freddychencsc@gmail.com
13 | */
14 | class DefaultCipher : AbstractCipher() {
15 |
16 | override fun encrypt(original: String?): String? {
17 | return original
18 | }
19 |
20 | override fun decrypt(original: String?): String? {
21 | return original
22 | }
23 |
24 | override fun getParamName(): String {
25 | return "params"
26 | }
27 | }
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/ShineKit.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin
2 |
3 | import com.freddy.shine.kotlin.config.ShineOptions
4 | import com.freddy.shine.kotlin.interf.IRequest
5 |
6 | /**
7 | * Shine核心类
8 | *
9 | * * [init] 初始化配置
10 | * * [getRequestManager] 获取请求管理器
11 | * @author: FreddyChen
12 | * @date : 2022/01/07 13:56
13 | * @email : freddychencsc@gmail.com
14 | */
15 | object ShineKit {
16 |
17 | var options: ShineOptions = ShineOptions.Builder().build()
18 |
19 | fun init(options: ShineOptions) {
20 | this.options = options
21 | }
22 |
23 | fun getRequestManager(): IRequest {
24 | return RequestManagerFactory.getRequestManager()
25 | }
26 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/freddy/shine/kotlin/example/CustomResponseModel1.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.example
2 |
3 | import com.freddy.shine.kotlin.model.IResponseModel
4 | import com.google.gson.annotations.SerializedName
5 |
6 | /**
7 | *
8 | * @author: FreddyChen
9 | * @date : 2022/01/17 16:05
10 | * @email : freddychencsc@gmail.com
11 | */
12 | data class CustomResponseModel1(
13 | @SerializedName("code")
14 | val code: String?,
15 | @SerializedName("day")
16 | val day: String?,
17 | @SerializedName("result")
18 | val result: T?
19 | ) : IResponseModel {
20 |
21 | override fun isSuccessful() = this.code == "1"
22 |
23 | override fun toString(): String {
24 | return "CustomResponseModel1(code=$code, day=$day, result=$result)"
25 | }
26 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/shine-kotlin/src/androidTest/java/com/freddy/shine/kotlin/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.freddy.shine.kotlin.test", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/shine-kotlin/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/freddy/shine/kotlin/example/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.example
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.freddy.shine.kotlin.example", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
22 |
23 |
--------------------------------------------------------------------------------
/app/src/main/java/com/freddy/shine/kotlin/example/TestRepository.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.example
2 |
3 | import com.freddy.shine.kotlin.config.RequestMethod
4 |
5 | /**
6 | *
7 | * @author: FreddyChen
8 | * @date : 2022/01/08 23:09
9 | * @email : freddychencsc@gmail.com
10 | */
11 | class TestRepository : BaseRepository() {
12 |
13 | /**
14 | * 获取历史列表数据
15 | * 异步请求
16 | */
17 | suspend fun fetchHistoryList(): ArrayList {
18 | return request(
19 | requestMethod = RequestMethod.POST,
20 | function = "lishi/api.php",
21 | )
22 | }
23 |
24 | /**
25 | * 获取新闻列表数据
26 | * 同步请求
27 | */
28 | fun fetchJournalismList(): ArrayList {
29 | return requestSync(
30 | requestMethod = RequestMethod.GET,
31 | baseUrl = "https://is.snssdk.com/",
32 | function = "api/news/feed/v51/",
33 | parserCls = CustomParser2::class,
34 | )
35 | }
36 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
16 |
17 |
26 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
16 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/retrofit/interceptor/OkHttpRequestHeaderInterceptor.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.retrofit.interceptor
2 |
3 | import com.freddy.shine.kotlin.retrofit.manager.RetrofitManager
4 | import okhttp3.Headers
5 | import okhttp3.Interceptor
6 | import okhttp3.Response
7 |
8 | /**
9 | * OkHttp请求头拦截器
10 | * @author: FreddyChen
11 | * @date : 2022/01/09 22:28
12 | * @email : freddychencsc@gmail.com
13 | */
14 | class OkHttpRequestHeaderInterceptor : OkHttpBaseInterceptor() {
15 |
16 | override fun intercept(chain: Interceptor.Chain): Response {
17 | val request = chain.request()
18 | val url = request.url.toString()
19 | return chain.proceed(request.newBuilder().headers(getHeaders(url)).build())
20 | }
21 |
22 | private fun getHeaders(url: String): Headers {
23 | val headersBuilder = Headers.Builder()
24 | RetrofitManager.INSTANCE.getHeaders(url)?.forEach {
25 | headersBuilder.add(it.key, it.value.toString())
26 | }
27 | return headersBuilder.build()
28 | }
29 | }
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/exception/RequestException.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.exception
2 |
3 | /**
4 | * 封装的请求异常
5 | *
6 | * * [type] 异常类型
7 | * * [url] 接口地址(baseUrl+function)
8 | * * [statusCode] http状态码
9 | * * [errCode] 业务错误码
10 | * * [errMsg] 业务错误信息
11 | * * [errBody] 错误详细信息
12 | * @author: FreddyChen
13 | * @date : 2022/01/07 16:19
14 | * @email : freddychencsc@gmail.com
15 | */
16 | class RequestException(
17 | val type: Type = Type.NATIVE,
18 | val url: String? = null,
19 | val statusCode: Int? = null,
20 | val errCode: Int? = null,
21 | val errMsg: String?,
22 | val errBody: String? = null
23 | ) : Throwable(errMsg) {
24 |
25 | /**
26 | * 异常类型
27 | *
28 | * [NATIVE] 本地异常
29 | * [NETWORK] 网络异常
30 | */
31 | enum class Type {
32 | NATIVE,
33 | NETWORK
34 | }
35 |
36 | override fun toString(): String {
37 | return "RequestException(type=$type, url=$url, statusCode=$statusCode, errCode=$errCode, errMsg=$errMsg)"
38 | }
39 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/utils/ShineLog.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.utils
2 |
3 | import android.util.Log
4 | import com.freddy.shine.kotlin.ShineKit
5 | import com.freddy.shine.kotlin.config.ShineConfig
6 |
7 | /**
8 | * Shine日志工具类
9 | *
10 | * @author: FreddyChen
11 | * @date : 2022/01/07 13:54
12 | * @email : freddychencsc@gmail.com
13 | */
14 | object ShineLog {
15 |
16 | fun v(tag: String = ShineKit.options.logTag, log: Any) {
17 | if (!ShineKit.options.logEnable) return
18 | Log.v(tag, log.toString())
19 | }
20 |
21 | fun d(tag: String = ShineKit.options.logTag, log: Any) {
22 | if (!ShineKit.options.logEnable) return
23 | Log.d(tag, log.toString())
24 | }
25 |
26 | fun i(tag: String = ShineKit.options.logTag, log: Any) {
27 | if (!ShineKit.options.logEnable) return
28 | Log.i(tag, log.toString())
29 | }
30 |
31 | fun w(tag: String = ShineKit.options.logTag, log: Any) {
32 | if (!ShineKit.options.logEnable) return
33 | Log.w(tag, log.toString())
34 | }
35 |
36 | fun e(tag: String = ShineKit.options.logTag, log: Any) {
37 | if (!ShineKit.options.logEnable) return
38 | Log.e(tag, log.toString())
39 | }
40 | }
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/interf/IRequest.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.interf
2 |
3 | import com.freddy.shine.kotlin.cipher.ICipher
4 | import com.freddy.shine.kotlin.config.RequestOptions
5 | import com.freddy.shine.kotlin.parser.DefaultParser
6 | import com.freddy.shine.kotlin.parser.IParser
7 | import java.lang.reflect.Type
8 | import kotlin.reflect.KClass
9 |
10 | /**
11 | * 抽象的接口请求封装,自定义RequestManager实现此接口即可
12 | *
13 | * @author: FreddyChen
14 | * @date : 2022/01/07 13:47
15 | * @email : freddychencsc@gmail.com
16 | */
17 | interface IRequest {
18 |
19 | /**
20 | * 异步请求
21 | * @param options 请求参数
22 | * @param type 数据类型映射
23 | * @param parserCls 数据解析器
24 | * @param cipherCls 数据加解密器
25 | */
26 | suspend fun request(
27 | options: RequestOptions,
28 | type: Type,
29 | parserCls: KClass,
30 | cipherCls: KClass? = null
31 | ): T
32 |
33 | /**
34 | * 同步请求
35 | * @param options 请求参数
36 | * @param type 数据类型映射
37 | * @param parserCls 数据解析器
38 | * @param cipherCls 数据加解密器
39 | */
40 | fun syncRequest(
41 | options: RequestOptions,
42 | type: Type,
43 | parserCls: KClass,
44 | cipherCls: KClass? = null
45 | ): T
46 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/freddy/shine/kotlin/example/CustomParser1.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.example
2 |
3 | import com.freddy.shine.kotlin.exception.RequestException
4 | import com.freddy.shine.kotlin.parser.AbstractParser
5 | import com.freddy.shine.kotlin.utils.ShineLog
6 | import java.lang.reflect.Type
7 |
8 | /**
9 | * 自定义的数据解析器,用于解析 [CustomResponseModel2] 格式数据
10 | * @author: FreddyChen
11 | * @date : 2022/01/07 14:16
12 | * @email : freddychencsc@gmail.com
13 | */
14 | class CustomParser1 : AbstractParser() {
15 |
16 | override fun parse(url: String, data: String, type: Type): T {
17 | ShineLog.i(log = "${javaClass.simpleName}#parse() data = $data, type = $type")
18 | var errMsg: String?
19 | var responseModel: CustomResponseModel1? = null
20 | try {
21 | responseModel = gson.fromJson>(
22 | data,
23 | CustomResponseModel1::class.java
24 | )
25 | if (!responseModel.isSuccessful()) {
26 | errMsg = "responseModel is failure"
27 | } else {
28 | return gson.fromJson(gson.toJson(responseModel.result), type)
29 | }
30 | } catch (e: Exception) {
31 | e.printStackTrace()
32 | errMsg = e.message
33 | }
34 |
35 | throw RequestException(
36 | type = RequestException.Type.NATIVE,
37 | url = url,
38 | errCode = -1,
39 | errMsg = "${javaClass.simpleName}#parse() failure\nerrMsg = $errMsg\ntype = $type\nresponseModel = $responseModel\ndata = $data"
40 | )
41 | }
42 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/freddy/shine/kotlin/example/CustomParser2.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.example
2 |
3 | import com.freddy.shine.kotlin.exception.RequestException
4 | import com.freddy.shine.kotlin.parser.AbstractParser
5 | import com.freddy.shine.kotlin.utils.ShineLog
6 | import java.lang.reflect.Type
7 |
8 | /**
9 | * 自定义的数据解析器,用于解析 [CustomResponseModel2] 格式数据
10 | * @author: FreddyChen
11 | * @date : 2022/01/07 14:16
12 | * @email : freddychencsc@gmail.com
13 | */
14 | class CustomParser2 : AbstractParser() {
15 |
16 | override fun parse(url: String, data: String, type: Type): T {
17 | ShineLog.i(log = "${javaClass.simpleName}#parse() data = $data, type = $type")
18 | var errMsg: String?
19 | var responseModel: CustomResponseModel2? = null
20 | try {
21 | responseModel = gson.fromJson>(
22 | data,
23 | CustomResponseModel2::class.java
24 | )
25 | if (!responseModel.isSuccessful()) {
26 | errMsg = "responseModel is failure"
27 | } else {
28 | return gson.fromJson(gson.toJson(responseModel.data), type)
29 | }
30 | } catch (e: Exception) {
31 | e.printStackTrace()
32 | errMsg = e.message
33 | }
34 |
35 | throw RequestException(
36 | type = RequestException.Type.NATIVE,
37 | url = url,
38 | errCode = -1,
39 | errMsg = "${javaClass.simpleName}#parse() failure\nerrMsg = $errMsg\ntype = $type\nresponseModel = $responseModel\ndata = $data"
40 | )
41 | }
42 | }
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/retrofit/interceptor/OkHttpLoggingInterceptor.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.retrofit.interceptor
2 |
3 | import com.freddy.shine.kotlin.utils.ShineLog
4 | import okhttp3.Interceptor
5 | import okhttp3.Response
6 | import java.lang.StringBuilder
7 |
8 | /**
9 | * OkHttp 日志拦截器
10 | * @author: FreddyChen
11 | * @date : 2022/01/09 19:10
12 | * @email : freddychencsc@gmail.com
13 | */
14 | class OkHttpLoggingInterceptor : OkHttpBaseInterceptor() {
15 |
16 | override fun intercept(chain: Interceptor.Chain): Response {
17 | val startTime = System.currentTimeMillis()
18 | val request = chain.request()
19 | val response = chain.proceed(request)
20 | val method = request.method
21 | val logBuilder = StringBuilder()
22 | val headerString: String? = if (request.headers.size == 0) {
23 | null
24 | } else {
25 | val headersBuilder = StringBuilder()
26 | request.headers.forEach {
27 | headersBuilder.append(it.first).append(":").append(it.second).append("\t")
28 | }
29 | headersBuilder.toString()
30 | }
31 | logBuilder.append("...\n接口地址:${request.url}")
32 | .append("\n请求方式:$method")
33 | .append("\n请求头:$headerString")
34 | .append("\n请求参数:${getRequestInfo(request, method)}")
35 | val endTime = System.currentTimeMillis()
36 | logBuilder.append("\n请求耗时:${endTime - startTime}ms")
37 | logBuilder.append("\n请求响应:${getResponseInfo(response)}")
38 | ShineLog.i(log = logBuilder.toString())
39 | return response
40 | }
41 | }
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/parser/DefaultParser.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.parser
2 |
3 | import com.freddy.shine.kotlin.exception.RequestException
4 | import com.freddy.shine.kotlin.model.DefaultResponseModel
5 | import com.freddy.shine.kotlin.utils.ShineLog
6 | import java.lang.reflect.Type
7 |
8 | /**
9 | * 默认数据解析器
10 | *
11 | * ResponseModel包含
12 | * * code
13 | * * msg
14 | * * data
15 | *
16 | * @see [DefaultResponseModel]
17 | * @author: FreddyChen
18 | * @date : 2022/01/06 17:52
19 | * @email : freddychencsc@gmail.com
20 | */
21 | internal class DefaultParser : AbstractParser() {
22 |
23 | override fun parse(url: String, data: String, type: Type): T {
24 | ShineLog.i(log = "${javaClass.simpleName}#parse() data = $data, type = $type")
25 | var errMsg: String?
26 | var responseModel: DefaultResponseModel? = null
27 | try {
28 | responseModel = gson.fromJson>(
29 | data,
30 | DefaultResponseModel::class.java
31 | )
32 | if (!responseModel.isSuccessful()) {
33 | errMsg = "responseModel is failure"
34 | } else {
35 | return gson.fromJson(gson.toJson(responseModel.data), type)
36 | }
37 | } catch (e: Exception) {
38 | e.printStackTrace()
39 | errMsg = e.message
40 | }
41 |
42 | throw RequestException(
43 | type = RequestException.Type.NATIVE,
44 | url = url,
45 | errCode = responseModel?.code ?: -1,
46 | errMsg = "${javaClass.simpleName}#parse() failure\nerrMsg = $errMsg\ntype = $type\nresponseModel = $responseModel\ndata = $data"
47 | )
48 | }
49 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/AbstractRequestManager.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin
2 |
3 | import com.freddy.shine.kotlin.exception.RequestException
4 | import com.freddy.shine.kotlin.interf.IRequest
5 | import com.freddy.shine.kotlin.parser.IParser
6 | import com.freddy.shine.kotlin.utils.ShineLog
7 | import com.google.gson.Gson
8 | import java.lang.reflect.Type
9 | import java.util.concurrent.ConcurrentHashMap
10 | import kotlin.reflect.KClass
11 |
12 | /**
13 | * RequestManager抽象类,自定义RequestManager需继承此类
14 | *
15 | * @author: FreddyChen
16 | * @date : 2022/01/07 14:05
17 | * @email : freddychencsc@gmail.com
18 | */
19 | abstract class AbstractRequestManager : IRequest {
20 |
21 | protected val gson: Gson by lazy { Gson() }
22 |
23 | private val parserMap: ConcurrentHashMap, IParser> by lazy {
24 | ConcurrentHashMap()
25 | }
26 |
27 | /**
28 | * 解析数据
29 | */
30 | protected fun parse(
31 | url: String,
32 | data: String,
33 | type: Type,
34 | parserCls: KClass
35 | ): T {
36 | return getParser(parserCls).parse(url, data, type)
37 | }
38 |
39 | /**
40 | * 获取Parser
41 | */
42 | private fun getParser(parserCls: KClass?): IParser {
43 | try {
44 | (parserCls ?: ShineKit.options.parserCls).apply {
45 | val parser: IParser = parserMap.getOrPut(parserCls) {
46 | Class.forName(java.name).newInstance() as IParser
47 | }
48 | ShineLog.i(log = "${this@AbstractRequestManager.javaClass.simpleName}#getParser() parser = $parser, parser = $parser")
49 | return parser
50 | }
51 | } catch (e: Exception) {
52 | e.printStackTrace()
53 | }
54 |
55 | throw RequestException(
56 | type = RequestException.Type.NATIVE,
57 | errMsg = "${this@AbstractRequestManager.javaClass.simpleName}#parse() parser为空"
58 | )
59 | }
60 | }
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'kotlin-android'
4 | }
5 |
6 | android {
7 | compileSdk 31
8 |
9 | defaultConfig {
10 | applicationId "com.freddy.shine.kotlin.example"
11 | minSdk 19
12 | targetSdk 31
13 | versionCode 1
14 | versionName "1.0"
15 |
16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 | multiDexEnabled true
18 | }
19 |
20 | buildTypes {
21 | release {
22 | minifyEnabled false
23 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
24 | }
25 | }
26 | compileOptions {
27 | sourceCompatibility JavaVersion.VERSION_1_8
28 | targetCompatibility JavaVersion.VERSION_1_8
29 | }
30 | kotlinOptions {
31 | jvmTarget = '1.8'
32 | }
33 | }
34 |
35 | dependencies {
36 | implementation 'androidx.core:core-ktx:1.3.2'
37 | implementation 'androidx.appcompat:appcompat:1.3.1'
38 | implementation 'com.google.android.material:material:1.4.0'
39 | testImplementation 'junit:junit:4.13.2'
40 | androidTestImplementation 'androidx.test.ext:junit:1.1.3'
41 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
42 |
43 | def kotlin_coroutines_version = '1.6.0'
44 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_version"
45 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$kotlin_coroutines_version"
46 |
47 | def lifecycle_version = '2.4.0'
48 | implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
49 |
50 | def gson_version = '2.8.9'
51 | implementation "com.google.code.gson:gson:$gson_version"
52 |
53 | def multidex_version = "2.0.1"
54 | implementation "androidx.multidex:multidex:$multidex_version"
55 |
56 | implementation project(":shine-kotlin")
57 | // def shine_kotlin_version = '0.0.5'
58 | // implementation "io.github.freddychen:shine-kotlin:$shine_kotlin_version"
59 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 | # Built application files
17 | *.apk
18 | *.aar
19 | *.ap_
20 | *.aab
21 |
22 | # Files for the ART/Dalvik VM
23 | *.dex
24 |
25 | # Java class files
26 | *.class
27 |
28 | # Generated files
29 | bin/
30 | gen/
31 | out/
32 | # Uncomment the following line in case you need and you don't have the release build type files in your app
33 | # release/
34 |
35 | # Gradle files
36 | .gradle/
37 | build/
38 |
39 | # Local configuration file (sdk path, etc)
40 |
41 | # Proguard folder generated by Eclipse
42 | proguard/
43 |
44 | # Log Files
45 | *.log
46 |
47 | # Android Studio Navigation editor temp files
48 | .navigation/
49 |
50 | # Android Studio captures folder
51 | captures/
52 |
53 | # IntelliJ
54 | .idea/workspace.xml
55 | .idea/tasks.xml
56 | .idea/gradle.xml
57 | .idea/assetWizardSettings.xml
58 | .idea/dictionaries
59 | .idea/libraries
60 | # Android Studio 3 in .gitignore file.
61 | .idea/caches
62 | .idea/modules.xml
63 | # Comment next line if keeping position of elements in Navigation Editor is relevant for you
64 | .idea/navEditor.xml
65 |
66 | # Keystore files
67 | # Uncomment the following lines if you do not want to check your keystore files in.
68 | #*.jks
69 | #*.keystore
70 |
71 | # External native build folder generated in Android Studio 2.2 and later
72 | .cxx/
73 |
74 | # Google Services (e.g. APIs or Firebase)
75 | # google-services.json
76 |
77 | # Freeline
78 | freeline.py
79 | freeline/
80 | freeline_project_description.json
81 |
82 | # fastlane
83 | fastlane/report.xml
84 | fastlane/Preview.html
85 | fastlane/screenshots
86 | fastlane/test_output
87 | fastlane/readme.md
88 |
89 | # Version control
90 | vcs.xml
91 |
92 | # lint
93 | lint/intermediates/
94 | lint/generated/
95 | lint/outputs/
96 | lint/tmp/
97 | # lint/reports/
98 |
99 | shine-kotlin/scripts/
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/config/ShineOptions.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.config
2 |
3 | import com.freddy.shine.kotlin.parser.DefaultParser
4 | import com.freddy.shine.kotlin.parser.IParser
5 | import kotlin.reflect.KClass
6 |
7 | /**
8 | * Shine配置类
9 | *
10 | * * logEnable 日志开关
11 | * * logTag 日志Tag
12 | * * baseUrl 默认baseUrl
13 | * * parserCls 默认数据解析器cls
14 | * @author: FreddyChen
15 | * @date : 2022/01/11 10:05
16 | * @email : freddychencsc@gmail.com
17 | */
18 | class ShineOptions(builder: Builder) {
19 |
20 | var logEnable: Boolean
21 | var logTag: String
22 | var baseUrl: String?
23 | var parserCls: KClass
24 |
25 | init {
26 | this.logEnable = builder.logEnable
27 | this.logTag = builder.logTag
28 | this.baseUrl = builder.baseUrl
29 | this.parserCls = builder.parserCls
30 | }
31 |
32 | class Builder {
33 | internal var logEnable: Boolean = ShineConfig.DEFAULT_LOG_ENABLE
34 | internal var logTag: String = ShineConfig.DEFAULT_LOG_TAG
35 | internal var baseUrl: String? = null
36 | internal var parserCls: KClass = DefaultParser::class
37 |
38 | fun setLogEnable(logEnable: Boolean): Builder {
39 | this.logEnable = logEnable
40 | return this
41 | }
42 |
43 | fun setLogTag(logTag: String): Builder {
44 | this.logTag = logTag
45 | return this
46 | }
47 |
48 | fun setBaseUrl(baseUrl: String): Builder {
49 | this.baseUrl = baseUrl
50 | return this
51 | }
52 |
53 | fun setParserCls(parserCls: KClass): Builder {
54 | this.parserCls = parserCls
55 | return this
56 | }
57 |
58 | fun build(): ShineOptions {
59 | return ShineOptions(this)
60 | }
61 | }
62 |
63 | override fun toString(): String {
64 | return "ShineOptions(logEnable=$logEnable, logTag='$logTag', baseUrl=$baseUrl, parserCls=$parserCls)"
65 | }
66 | }
--------------------------------------------------------------------------------
/shine-kotlin/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'kotlin-android'
4 | }
5 |
6 | android {
7 | compileSdk 31
8 |
9 | defaultConfig {
10 | minSdk 19
11 | targetSdk 31
12 | versionCode 1
13 | versionName "1.0"
14 |
15 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
16 | consumerProguardFiles "consumer-rules.pro"
17 | }
18 |
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
23 | }
24 | }
25 | compileOptions {
26 | sourceCompatibility JavaVersion.VERSION_1_8
27 | targetCompatibility JavaVersion.VERSION_1_8
28 | }
29 | kotlinOptions {
30 | jvmTarget = '1.8'
31 | }
32 | }
33 |
34 | dependencies {
35 | implementation 'androidx.core:core-ktx:1.3.2'
36 | implementation 'androidx.appcompat:appcompat:1.3.1'
37 | implementation 'com.google.android.material:material:1.4.0'
38 | testImplementation 'junit:junit:4.13.2'
39 | androidTestImplementation 'androidx.test.ext:junit:1.1.3'
40 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
41 |
42 | def kotlin_version = '1.6.0'
43 | implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
44 |
45 | def kotlin_coroutines_version = '1.6.0'
46 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_version"
47 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$kotlin_coroutines_version"
48 |
49 | def retrofit_version = '2.9.0'
50 | implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
51 | implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"
52 |
53 | def gson_version = '2.8.9'
54 | implementation "com.google.code.gson:gson:$gson_version"
55 |
56 | def okhttp_version = '4.9.3'
57 | implementation "com.squareup.okhttp3:okhttp:$okhttp_version"
58 | }
59 |
60 | ext {
61 | PUBLISH_GROUP_ID = "io.github.freddychen" // 项目包名
62 | PUBLISH_ARTIFACT_ID = 'shine-kotlin' // 项目名
63 | PUBLISH_VERSION = '0.0.8' // 版本号
64 | }
65 | apply from: './scripts/publish-mavencentral.gradle'
--------------------------------------------------------------------------------
/app/src/main/java/com/freddy/shine/kotlin/example/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.example
2 |
3 | import androidx.appcompat.app.AppCompatActivity
4 | import android.os.Bundle
5 | import android.util.Log
6 | import android.view.View
7 | import androidx.lifecycle.lifecycleScope
8 | import com.freddy.shine.kotlin.exception.RequestException
9 | import com.freddy.shine.kotlin.ShineKit
10 | import com.freddy.shine.kotlin.config.ShineOptions
11 | import kotlinx.coroutines.CoroutineScope
12 | import kotlinx.coroutines.Dispatchers
13 | import kotlinx.coroutines.launch
14 | import kotlin.concurrent.thread
15 |
16 | class MainActivity : AppCompatActivity() {
17 |
18 | companion object {
19 | private const val TAG = "MainActivity"
20 | }
21 |
22 | private lateinit var btn1: View
23 | private lateinit var btn2: View
24 |
25 | override fun onCreate(savedInstanceState: Bundle?) {
26 | super.onCreate(savedInstanceState)
27 | setContentView(R.layout.activity_main)
28 | val options = ShineOptions.Builder()
29 | .setLogEnable(true)
30 | .setLogTag("FreddyChen")
31 | .setBaseUrl("https://api.oick.cn/")
32 | .setParserCls(CustomParser1::class)
33 | .build()
34 | ShineKit.init(options)
35 |
36 | val repository = TestRepository()
37 |
38 | btn1 = findViewById(R.id.btn_1)
39 | btn2 = findViewById(R.id.btn_2)
40 |
41 | btn1.setOnClickListener {
42 | thread(start = true) {
43 | Log.i(TAG, "异步请求开始")
44 | lifecycleScope.launch(Dispatchers.IO) {
45 | try {
46 | val historyList = repository.fetchHistoryList()
47 | Log.i(TAG, "historyList = $historyList")
48 | } catch (e: RequestException) {
49 | Log.e(TAG, "e = $e")
50 | }
51 | }
52 | Log.i(TAG, "异步请求结束")
53 | }
54 | }
55 |
56 | btn2.setOnClickListener {
57 | thread(start = true) {
58 | try {
59 | Log.i(TAG, "同步请求开始")
60 | val journalismList = repository.fetchJournalismList()
61 | Log.i(TAG, "journalismList = $journalismList")
62 | Log.i(TAG, "同步请求结束")
63 | } catch (e: RequestException) {
64 | Log.e(TAG, "e = $e")
65 | }
66 | }
67 | }
68 | }
69 | }
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/config/RequestOptions.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.config
2 |
3 | import android.util.ArrayMap
4 | import com.freddy.shine.kotlin.parser.DefaultParser
5 | import com.freddy.shine.kotlin.parser.IParser
6 | import kotlin.reflect.KClass
7 |
8 | /**
9 | * 请求配置
10 | *
11 | * * requestMethod 请求方式
12 | * * baseUrl baseUrl
13 | * * function 接口地址
14 | * * headers 请求头
15 | * * params 请求参数
16 | * * contentType contentType
17 | * @author: FreddyChen
18 | * @date : 2022/01/06 17:42
19 | * @email : freddychencsc@gmail.com
20 | */
21 | class RequestOptions private constructor(builder: Builder) {
22 |
23 | val requestMethod: RequestMethod
24 | val baseUrl: String?
25 | val function: String?
26 | val headers: ArrayMap?
27 | val params: ArrayMap?
28 | val contentType: String
29 |
30 | init {
31 | this.requestMethod = builder.requestMethod
32 | this.baseUrl = builder.baseUrl
33 | this.function = builder.function
34 | this.headers = builder.headers
35 | this.params = builder.params
36 | this.contentType = builder.contentType
37 | }
38 |
39 | class Builder {
40 | internal var requestMethod: RequestMethod = RequestMethod.GET
41 | internal var baseUrl: String? = null
42 | internal var function: String? = null
43 | internal var headers: ArrayMap? = null
44 | internal var params: ArrayMap? = null
45 | internal var contentType: String = NetworkConfig.DEFAULT_CONTENT_TYPE
46 |
47 | fun setRequestMethod(requestMethod: RequestMethod): Builder {
48 | this.requestMethod = requestMethod
49 | return this
50 | }
51 |
52 | fun setBaseUrl(baseUrl: String): Builder {
53 | this.baseUrl = baseUrl
54 | return this
55 | }
56 |
57 | fun setFunction(function: String): Builder {
58 | this.function = function
59 | return this
60 | }
61 |
62 | fun setHeaders(headers: ArrayMap): Builder {
63 | this.headers = headers
64 | return this
65 | }
66 |
67 | fun setParams(params: ArrayMap): Builder {
68 | this.params = params
69 | return this
70 | }
71 |
72 | fun setContentType(contentType: String): Builder {
73 | this.contentType = contentType
74 | return this
75 | }
76 |
77 | fun build(): RequestOptions {
78 | return RequestOptions(this)
79 | }
80 | }
81 |
82 | override fun toString(): String {
83 | return "RequestOptions(requestMethod=$requestMethod, baseUrl='$baseUrl', function=$function, headers=$headers, params=$params, contentType='$contentType')"
84 | }
85 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/freddy/shine/kotlin/example/BaseRepository.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.example
2 |
3 | import android.util.ArrayMap
4 | import com.freddy.shine.kotlin.ShineKit
5 | import com.freddy.shine.kotlin.cipher.ICipher
6 | import com.freddy.shine.kotlin.config.NetworkConfig
7 | import com.freddy.shine.kotlin.config.RequestMethod
8 | import com.freddy.shine.kotlin.config.RequestOptions
9 | import com.freddy.shine.kotlin.parser.IParser
10 | import com.google.gson.reflect.TypeToken
11 | import kotlin.reflect.KClass
12 |
13 | /**
14 | * @author: FreddyChen
15 | * @date : 2022/01/09 03:54
16 | * @email : freddychencsc@gmail.com
17 | */
18 | open class BaseRepository {
19 |
20 | /**
21 | * 异步请求
22 | */
23 | suspend inline fun request(
24 | requestMethod: RequestMethod,
25 | baseUrl: String = "https://api.oick.cn/",
26 | function: String,
27 | headers: ArrayMap? = null,
28 | params: ArrayMap? = null,
29 | contentType: String = NetworkConfig.DEFAULT_CONTENT_TYPE,
30 | parserCls: KClass = CustomParser1::class,
31 | cipherCls: KClass? = null
32 | ): T {
33 | val optionsBuilder = RequestOptions.Builder()
34 | .setRequestMethod(requestMethod)
35 | .setBaseUrl(baseUrl)
36 | .setFunction(function)
37 | .setContentType(contentType)
38 |
39 | if (!headers.isNullOrEmpty()) {
40 | optionsBuilder.setHeaders(headers)
41 | }
42 |
43 | if (!params.isNullOrEmpty()) {
44 | optionsBuilder.setParams(params)
45 | }
46 |
47 | return ShineKit.getRequestManager()
48 | .request(optionsBuilder.build(), object : TypeToken() {}.type, parserCls, cipherCls)
49 | }
50 |
51 | /**
52 | * 异步请求
53 | */
54 | inline fun requestSync(
55 | requestMethod: RequestMethod,
56 | baseUrl: String = "https://www.wanandroid.com/",
57 | function: String,
58 | headers: ArrayMap? = null,
59 | params: ArrayMap? = null,
60 | contentType: String = NetworkConfig.DEFAULT_CONTENT_TYPE,
61 | parserCls: KClass = CustomParser1::class,
62 | cipherCls: KClass? = null
63 | ): T {
64 | val optionsBuilder = RequestOptions.Builder()
65 | .setRequestMethod(requestMethod)
66 | .setBaseUrl(baseUrl)
67 | .setFunction(function)
68 | .setContentType(contentType)
69 |
70 | if (!headers.isNullOrEmpty()) {
71 | optionsBuilder.setHeaders(headers)
72 | }
73 |
74 | if (!params.isNullOrEmpty()) {
75 | optionsBuilder.setParams(params)
76 | }
77 |
78 | return ShineKit.getRequestManager()
79 | .syncRequest(
80 | optionsBuilder.build(),
81 | object : TypeToken() {}.type,
82 | parserCls,
83 | cipherCls
84 | )
85 | }
86 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/retrofit/interceptor/OkHttpResponseDecryptInterceptor.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.retrofit.interceptor
2 |
3 | import com.freddy.shine.kotlin.config.RequestMethod
4 | import com.freddy.shine.kotlin.retrofit.manager.RetrofitManager
5 | import com.freddy.shine.kotlin.utils.ShineLog
6 | import okhttp3.Interceptor
7 | import okhttp3.Response
8 | import okhttp3.ResponseBody.Companion.toResponseBody
9 |
10 | /**
11 | * OkHttp请求数据解密拦截器
12 | * @author: FreddyChen
13 | * @date : 2022/01/13 15:05
14 | * @email : freddychencsc@gmail.com
15 | */
16 | class OkHttpResponseDecryptInterceptor : OkHttpBaseInterceptor() {
17 |
18 | companion object {
19 | private const val TAG = "OkHttpResponseDecryptInterceptor"
20 | }
21 |
22 | override fun intercept(chain: Interceptor.Chain): Response {
23 | val request = chain.request()
24 | var response = chain.proceed(request)
25 | val requestUrl = request.url
26 | val urlString = requestUrl.toString()
27 | val requestMethod = getRequestMethod(request.method) ?: return response
28 | val url: String = when (requestMethod) {
29 | RequestMethod.GET, RequestMethod.DELETE -> {
30 | if (requestUrl.encodedQuery.isNullOrEmpty()) {
31 | urlString
32 | } else {
33 | urlString.substring(
34 | 0,
35 | urlString.indexOf("?")
36 | )
37 | }
38 | }
39 | RequestMethod.POST, RequestMethod.PUT -> {
40 | urlString
41 | }
42 | else -> {
43 | urlString
44 | }
45 | }
46 | if (response.isSuccessful) {
47 | val responseBody = response.body
48 | responseBody?.let { body ->
49 | try {
50 | RetrofitManager.INSTANCE.getCipher(url)?.apply {
51 | val source = body.source()
52 | source.request(Long.MAX_VALUE)
53 | val buffer = source.buffer
54 | var charset = Charsets.UTF_8
55 | val contentType = body.contentType()
56 | contentType?.apply {
57 | charset = contentType.charset(charset)!!
58 | }
59 | val responseData = buffer.clone().readString(charset).trim()
60 | val decryptData = decrypt(responseData)
61 | val newResponseBody = decryptData?.toResponseBody(contentType)
62 | response = response.newBuilder().body(newResponseBody).build()
63 | ShineLog.i(log = "${TAG}#intercept() \nresponseBody = $body\nnewResponseBody = $newResponseBody\nresponseData = $responseData\ndecryptData = $decryptData")
64 | }
65 | } catch (e: Exception) {
66 | e.printStackTrace()
67 | ShineLog.e(log = "${TAG}#intercept() decrypt failure, reason:${e.message}")
68 | }
69 | }
70 | }
71 | RetrofitManager.INSTANCE.removeCipherCls(url)
72 | return response
73 | }
74 | }
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/retrofit/interceptor/OkHttpBaseInterceptor.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.retrofit.interceptor
2 |
3 | import com.freddy.shine.kotlin.config.RequestMethod
4 | import okhttp3.Interceptor
5 | import okhttp3.Request
6 | import okhttp3.Response
7 | import okio.Buffer
8 | import java.io.IOException
9 | import java.lang.StringBuilder
10 | import java.nio.charset.Charset
11 |
12 | /**
13 | * OkHttp拦截器基类,所有OkHttp拦截器都继承此类
14 | *
15 | * @see [OkHttpLoggingInterceptor]
16 | * @author: FreddyChen
17 | * @date : 2022/01/09 19:11
18 | * @email : freddychencsc@gmail.com
19 | */
20 | abstract class OkHttpBaseInterceptor : Interceptor {
21 |
22 | open fun getRequestInfo(request: Request, method: String): String? {
23 | val requestMethod = getRequestMethod(method) ?: return null
24 | when (requestMethod) {
25 | RequestMethod.GET, RequestMethod.DELETE -> {
26 | val httpUrl = request.url
27 | val paramKeys = httpUrl.queryParameterNames
28 | if (paramKeys.isNullOrEmpty()) {
29 | return null
30 | }
31 | val resultBuilder = StringBuilder()
32 | for (key in paramKeys) {
33 | val value = httpUrl.queryParameter(key)
34 | resultBuilder.append("$key=$value\n")
35 | }
36 | resultBuilder.deleteAt(resultBuilder.length - 1)
37 | return resultBuilder.toString()
38 | }
39 | RequestMethod.POST, RequestMethod.PUT -> {
40 | val requestBody = request.body ?: return null
41 | try {
42 | val bufferedSink = Buffer()
43 | requestBody.writeTo(bufferedSink)
44 | val charset: Charset = Charsets.UTF_8
45 | return bufferedSink.readString(charset)
46 | } catch (e: IOException) {
47 | e.printStackTrace()
48 | }
49 | }
50 | }
51 | return null
52 | }
53 |
54 | open fun getResponseInfo(response: Response): String? {
55 | var str: String? = null
56 | // if (!response.isSuccessful) {
57 | // return response.message
58 | // }
59 | val responseBody = response.body
60 | responseBody?.apply {
61 | val contentLength = contentLength()
62 | val source = responseBody.source()
63 | try {
64 | source.request(Long.MAX_VALUE)
65 | } catch (e: IOException) {
66 | e.printStackTrace()
67 | }
68 | val buffer = source.buffer
69 | val charset = Charset.forName(Charsets.UTF_8.name())
70 | if (contentLength != 0L) {
71 | str = buffer.clone().readString(charset)
72 | }
73 | return str
74 | }
75 |
76 | return null
77 | }
78 |
79 | protected open fun getRequestMethod(method: String): RequestMethod? {
80 | var requestMethod: RequestMethod? = null
81 | when (method.uppercase()) {
82 | "GET" -> {
83 | requestMethod = RequestMethod.GET
84 | }
85 | "POST" -> {
86 | requestMethod = RequestMethod.POST
87 | }
88 | "PUT" -> {
89 | requestMethod = RequestMethod.PUT
90 | }
91 | "DELETE" -> {
92 | requestMethod = RequestMethod.DELETE
93 | }
94 | }
95 | return requestMethod
96 | }
97 | }
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/retrofit/converter/StringConverterFactory.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.retrofit.converter
2 |
3 | import com.freddy.shine.kotlin.config.NetworkConfig
4 | import okhttp3.MediaType
5 | import okhttp3.MediaType.Companion.toMediaTypeOrNull
6 | import okhttp3.RequestBody
7 | import okhttp3.RequestBody.Companion.toRequestBody
8 | import okhttp3.ResponseBody
9 | import retrofit2.Converter
10 | import retrofit2.Retrofit
11 | import java.io.ByteArrayOutputStream
12 | import java.io.Closeable
13 | import java.io.IOException
14 | import java.io.InputStream
15 | import java.lang.reflect.Type
16 |
17 | /**
18 | * 自定义StringConverterFactory
19 | * @author: FreddyChen
20 | * @date : 2022/01/07 16:15
21 | * @email : freddychencsc@gmail.com
22 | */
23 | class StringConverterFactory : Converter.Factory() {
24 |
25 | companion object {
26 | private val MEDIA_TYPE: MediaType? = NetworkConfig.DEFAULT_CONTENT_TYPE.toMediaTypeOrNull()
27 | private const val UTF_8 = "UTF-8"
28 | private const val BUFFER_SIZE = 4096
29 |
30 | fun create(): StringConverterFactory {
31 | return StringConverterFactory()
32 | }
33 | }
34 |
35 | override fun responseBodyConverter(
36 | type: Type, annotations: Array?,
37 | retrofit: Retrofit?
38 | ): Converter? {
39 | return if (String::class.java == type) {
40 | Converter { value -> getStringFrom(value) }
41 | } else null
42 | }
43 |
44 | override fun requestBodyConverter(
45 | type: Type, parameterAnnotations: Array?,
46 | methodAnnotations: Array?, retrofit: Retrofit?
47 | ): Converter<*, RequestBody?>? {
48 | return if (String::class.java == type) {
49 | Converter { value -> value.toRequestBody(MEDIA_TYPE) }
50 | } else null
51 | }
52 |
53 | @Throws(IOException::class)
54 | private fun getStringFrom(value: ResponseBody): String? {
55 | val inputStream = value.byteStream()
56 | return getStringFrom(inputStream)
57 | }
58 |
59 | @Throws(IOException::class)
60 | private fun getStringFrom(inputStream: InputStream?): String? {
61 | var result: String? = null
62 | try {
63 | if (inputStream != null) {
64 | result = writeStreamToString(inputStream)
65 | }
66 | } finally {
67 | closeQuietly(inputStream)
68 | }
69 | return result
70 | }
71 |
72 | @Throws(IOException::class)
73 | private fun writeStreamToString(inputStream: InputStream): String? {
74 | val result: String?
75 | val outputStream = ByteArrayOutputStream()
76 | result = try {
77 | readStreamAndConvert(inputStream, outputStream)
78 | } finally {
79 | closeQuietly(outputStream)
80 | }
81 | return result
82 | }
83 |
84 | @Throws(IOException::class)
85 | private fun readStreamAndConvert(
86 | inputStream: InputStream,
87 | outputStream: ByteArrayOutputStream
88 | ): String? {
89 | val buffer = ByteArray(BUFFER_SIZE)
90 | var length: Int
91 | while (inputStream.read(buffer).also { length = it } != -1) {
92 | outputStream.write(buffer, 0, length)
93 | }
94 | return outputStream.toString(UTF_8)
95 | }
96 |
97 | private fun closeQuietly(stream: Closeable?) {
98 | try {
99 | stream?.close()
100 | } catch (ex: Exception) {
101 | ex.printStackTrace()
102 | }
103 | }
104 | }
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/retrofit/api/IApiService.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.retrofit.api
2 |
3 | import android.util.ArrayMap
4 | import okhttp3.RequestBody
5 | import retrofit2.Call
6 | import retrofit2.http.*
7 |
8 | /**
9 | * 统一的请求方式
10 | *
11 | * * [get] function: String
12 | * * [get] function: String, params: ArrayMap
13 | * * [post] function: String
14 | * * [post] function: String, body: RequestBody
15 | * * [put] function: String
16 | * * [put] function: String, body: RequestBody
17 | * * [delete] function: String
18 | * * [delete] function: String, body: RequestBody
19 | * * [syncGet] function: String
20 | * * [syncGet] function: String, body: RequestBody
21 | * * [syncPost] function: String
22 | * * [syncPost] function: String, body: RequestBody
23 | * * [syncPut] function: String
24 | * * [syncPut] function: String, body: RequestBody
25 | * * [syncDelete] function: String
26 | * * [syncDelete] function: String, body: RequestBody
27 | * @author: FreddyChen
28 | * @date : 2022/01/07 11:08
29 | * @email : freddychencsc@gmail.com
30 | */
31 | internal interface IApiService {
32 |
33 | /**
34 | * 异步GET请求
35 | * 无参
36 | */
37 | @GET
38 | suspend fun get(@Url function: String): String
39 |
40 | /**
41 | * 异步GET请求
42 | * 带参
43 | */
44 | @GET
45 | suspend fun get(@Url function: String, @QueryMap params: ArrayMap): String
46 |
47 | /**
48 | * 异步POST请求
49 | * 无参
50 | */
51 | @POST
52 | suspend fun post(@Url function: String): String
53 |
54 | /**
55 | * 异步POST请求
56 | * 带参
57 | */
58 | @POST
59 | suspend fun post(@Url function: String, @Body body: RequestBody): String
60 |
61 | /**
62 | * 异步PUT请求
63 | * 无参
64 | */
65 | @PUT
66 | suspend fun put(@Url function: String): String
67 |
68 | /**
69 | * 异步PUT请求
70 | * 带参
71 | */
72 | @PUT
73 | suspend fun put(@Url function: String, @Body body: RequestBody): String
74 |
75 | /**
76 | * 异步DELETE请求
77 | * 无参
78 | */
79 | @DELETE
80 | suspend fun delete(@Url function: String): String
81 |
82 | /**
83 | * 异步DELETE请求
84 | * 带参
85 | */
86 | @DELETE
87 | suspend fun delete(@Url function: String, @QueryMap params: ArrayMap): String
88 |
89 | /**
90 | * 同步GET请求
91 | * 无参
92 | */
93 | @GET
94 | fun syncGet(@Url function: String): Call
95 |
96 | /**
97 | * 同步GET请求
98 | * 带参
99 | */
100 | @GET
101 | fun syncGet(@Url function: String, @QueryMap params: ArrayMap): Call
102 |
103 | /**
104 | * 同步POST请求
105 | * 无参
106 | */
107 | @POST
108 | fun syncPost(@Url function: String): Call
109 |
110 | /**
111 | * 同步POST请求
112 | * 带参
113 | */
114 | @POST
115 | fun syncPost(@Url function: String, @Body body: RequestBody): Call
116 |
117 | /**
118 | * 同步PUT请求
119 | * 无参
120 | */
121 | @PUT
122 | fun syncPut(@Url function: String): Call
123 |
124 | /**
125 | * 同步PUT请求
126 | * 带参
127 | */
128 | @PUT
129 | fun syncPut(@Url function: String, @Body body: RequestBody): Call
130 |
131 | /**
132 | * 同步DELETE请求
133 | * 无参
134 | */
135 | @DELETE
136 | fun syncDelete(@Url function: String): Call
137 |
138 | /**
139 | * 同步DELETE请求
140 | * 带参
141 | */
142 | @DELETE
143 | fun syncDelete(@Url function: String, @QueryMap params: ArrayMap): Call
144 | }
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/retrofit/interceptor/OkHttpRequestEncryptInterceptor.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.retrofit.interceptor
2 |
3 | import com.freddy.shine.kotlin.config.RequestMethod
4 | import com.freddy.shine.kotlin.retrofit.manager.RetrofitManager
5 | import com.freddy.shine.kotlin.utils.ShineLog
6 | import okhttp3.Interceptor
7 | import okhttp3.RequestBody.Companion.toRequestBody
8 | import okhttp3.Response
9 | import okio.Buffer
10 | import java.net.URLDecoder
11 | import java.nio.charset.Charset
12 |
13 | /**
14 | * OkHttp请求数据加密拦截器
15 | * @author: FreddyChen
16 | * @date : 2022/01/13 15:05
17 | * @email : freddychencsc@gmail.com
18 | */
19 | class OkHttpRequestEncryptInterceptor : OkHttpBaseInterceptor() {
20 |
21 | companion object {
22 | private const val TAG = "OkHttpRequestEncryptInterceptor"
23 | }
24 |
25 | override fun intercept(chain: Interceptor.Chain): Response {
26 | var request = chain.request()
27 | val requestMethod = getRequestMethod(request.method) ?: return chain.proceed(request)
28 | val url = request.url
29 | val urlString = url.toString()
30 | when (requestMethod) {
31 | RequestMethod.GET, RequestMethod.DELETE -> {
32 | if (!url.encodedQuery.isNullOrEmpty()) {
33 | try {
34 | val api = "${url.scheme}://${url.host}:${url.port}${url.encodedPath}".trim()
35 | RetrofitManager.INSTANCE.getCipher(
36 | urlString.substring(
37 | 0,
38 | urlString.indexOf("?")
39 | )
40 | )?.apply {
41 | val newApi = "${api}?${getParamName()}=${encrypt(url.encodedQuery)}"
42 | request = request.newBuilder().url(newApi).build()
43 | ShineLog.i(log = "${TAG}#intercept() \napi = $api\nnewApi = $newApi")
44 | }
45 | } catch (e: Exception) {
46 | e.printStackTrace()
47 | ShineLog.e(log = "${TAG}#intercept() encrypt failure, reason:${e.message}")
48 | chain.proceed(request)
49 | }
50 | }
51 | }
52 |
53 | RequestMethod.POST, RequestMethod.PUT -> {
54 | request.body?.let { body ->
55 | var charset: Charset? = null
56 | val contentType = body.contentType()
57 | if (contentType != null) {
58 | charset = contentType.charset(Charsets.UTF_8)
59 | // 如果contentType为multipart,则不进行加密
60 | if (contentType.type.lowercase() == "multipart") {
61 | return chain.proceed(request)
62 | }
63 | }
64 | try {
65 | RetrofitManager.INSTANCE.getCipher(urlString)?.apply {
66 | val buffer = Buffer()
67 | body.writeTo(buffer)
68 | val requestData = URLDecoder.decode(
69 | buffer.readString(charset!!).trim(),
70 | Charsets.UTF_8.name()
71 | )
72 | val encryptData = encrypt(requestData)
73 | encryptData?.apply {
74 | val newRequestBody = toRequestBody(contentType)
75 | val newRequestBuilder = request.newBuilder()
76 | when (requestMethod) {
77 | RequestMethod.POST -> {
78 | newRequestBuilder.post(newRequestBody)
79 | }
80 | RequestMethod.PUT -> {
81 | newRequestBuilder.put(newRequestBody)
82 | }
83 | }
84 | request = newRequestBuilder.build()
85 | ShineLog.i(log = "${TAG}#intercept() \nrequestBody = $body\nnewRequestBody = $newRequestBody\nrequestData = $requestData\nencryptData = $encryptData")
86 | }
87 | }
88 | } catch (e: Exception) {
89 | e.printStackTrace()
90 | ShineLog.e(log = "${TAG}#intercept() encrypt failure, reason:${e.message}")
91 | chain.proceed(request)
92 | }
93 | }
94 | }
95 | }
96 | return chain.proceed(request)
97 | }
98 | }
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/retrofit/manager/RetrofitManager.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.retrofit.manager
2 |
3 | import android.util.ArrayMap
4 | import com.freddy.shine.kotlin.cipher.ICipher
5 | import com.freddy.shine.kotlin.retrofit.converter.StringConverterFactory
6 | import com.freddy.shine.kotlin.retrofit.interceptor.OkHttpLoggingInterceptor
7 | import com.freddy.shine.kotlin.retrofit.interceptor.OkHttpResponseDecryptInterceptor
8 | import com.freddy.shine.kotlin.retrofit.interceptor.OkHttpRequestEncryptInterceptor
9 | import com.freddy.shine.kotlin.retrofit.interceptor.OkHttpRequestHeaderInterceptor
10 | import com.freddy.shine.kotlin.utils.ShineLog
11 | import okhttp3.OkHttpClient
12 | import retrofit2.Retrofit
13 | import java.util.concurrent.ConcurrentHashMap
14 | import java.util.concurrent.TimeUnit
15 | import kotlin.reflect.KClass
16 |
17 | /**
18 | * Retrofit管理类,提供获取OkHttpClient、Retrofit等方法
19 | * @author: FreddyChen
20 | * @date : 2022/01/07 14:48
21 | * @email : freddychencsc@gmail.com
22 | */
23 | class RetrofitManager private constructor() {
24 |
25 | companion object {
26 | val INSTANCE: RetrofitManager by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
27 | RetrofitManager()
28 | }
29 | }
30 |
31 | /**
32 | * Retrofit集合
33 | * key: baseUrl
34 | * value: Retrofit
35 | */
36 | private val retrofitMap: ConcurrentHashMap by lazy {
37 | ConcurrentHashMap()
38 | }
39 |
40 | /**
41 | * 加解密器Cls集合
42 | * key: url(baseUrl+function)
43 | * value: Cipher Clazz
44 | */
45 | private val cipherClsMap: HashMap?> by lazy {
46 | hashMapOf()
47 | }
48 |
49 | /**
50 | * 加解密器集合
51 | * key: Cipher Clazz
52 | * value: Cipher instance
53 | */
54 | private val cipherMap: ConcurrentHashMap, ICipher> by lazy {
55 | ConcurrentHashMap()
56 | }
57 |
58 | /**
59 | * 请求头集合
60 | * key: url(baseUrl+function)
61 | * value: headers
62 | */
63 | private val headersMap: HashMap?> by lazy {
64 | hashMapOf()
65 | }
66 |
67 | /**
68 | * 获取OkHttpClient
69 | *
70 | * @return
71 | */
72 | private fun getOkHttpClient(): OkHttpClient {
73 | val timeout = 60 * 1000L
74 | val builder = OkHttpClient.Builder()
75 | .connectTimeout(timeout, TimeUnit.MILLISECONDS)
76 | .readTimeout(timeout, TimeUnit.MILLISECONDS)
77 | .writeTimeout(timeout, TimeUnit.MILLISECONDS)
78 | .addInterceptor(OkHttpRequestHeaderInterceptor())
79 | .addInterceptor(OkHttpLoggingInterceptor())
80 | .addInterceptor(OkHttpRequestEncryptInterceptor())
81 | .addInterceptor(OkHttpResponseDecryptInterceptor())
82 | return builder.build()
83 | }
84 |
85 | /**
86 | * 根据baseUrl获取对应的Retrofit实例
87 | * 首次获取时同时保存起来,方便下次直接获取
88 | */
89 | fun getRetrofit(baseUrl: String): Retrofit {
90 | return retrofitMap.getOrPut(baseUrl) {
91 | Retrofit.Builder()
92 | .baseUrl(baseUrl)
93 | .addConverterFactory(StringConverterFactory.create())
94 | .client(getOkHttpClient())
95 | .build()
96 | }
97 | }
98 |
99 | /**
100 | * 临时保存接口请求头
101 | * @param url baseUrl+function
102 | */
103 | fun saveHeaders(url: String, headers: ArrayMap?) {
104 | if (headersMap.containsKey(url)) return
105 | headersMap[url] = headers
106 | }
107 |
108 | /**
109 | * 获取接口请求头,并移除
110 | * @param url baseUrl+function
111 | */
112 | fun getHeaders(url: String): ArrayMap? {
113 | if (!headersMap.containsKey(url)) return null
114 | val headers = headersMap[url]
115 | headers?.apply {
116 | headersMap.remove(url)
117 | }
118 | return headers
119 | }
120 |
121 | /**
122 | * 临时保存接口加解密器
123 | * @param url baseUrl+function
124 | */
125 | fun saveCipher(url: String, cipherCls: KClass?) {
126 | if(cipherClsMap.containsKey(url)) return
127 | cipherClsMap[url] = cipherCls
128 | }
129 |
130 | /**
131 | * 获取接口加解密器
132 | * @param url baseUrl+function
133 | */
134 | fun getCipher(url: String): ICipher? {
135 | val cipherCls = cipherClsMap[url] ?: return null
136 | val cipher: ICipher = cipherMap.getOrPut(cipherCls) {
137 | Class.forName(cipherCls.java.name).newInstance() as ICipher
138 | }
139 | ShineLog.i(log = "RetrofitManager#getCipher() \nurl = $url\ncipherCls = $cipherCls\ncipher = $cipher")
140 | return cipher
141 | }
142 |
143 | /**
144 | * 移除接口加解密器
145 | */
146 | fun removeCipherCls(url: String) {
147 | if (!cipherClsMap.containsKey(url)) return
148 | cipherClsMap.remove(url)
149 | }
150 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Shine-Kotlin
2 | 基于Retrofit+Kotlin协程实现的Kotlin网络请求库封装,支持GET/POST/PUT/DELETE请求、动态BaseUrl、请求头、请求/响应日志、自定义加解密器等。同时,支持自定义Parser(数据解析器),用于解决不同返回数据Model。
3 |
4 | ## 文章链接
5 | [Shine——更简单的Android网络请求库封装](https://juejin.cn/user/2084329776750989/posts)
6 |
7 | ## 使用方式
8 | 1. 添加依赖
9 | * **Java**
10 | `implementation "io.github.freddychen:shine-java:$lastest_version"`
11 | * **Kotlin**
12 | `implementation "io.github.freddychen:shine-kotlin:$lastest_version"`
13 |
14 |
15 | *Note:最新版本可在[maven central shine](https://search.maven.org/artifact/io.github.freddychen/shine-kotlin)中找到。*
16 |
17 | 2. 初始化
18 | 使用**Shine**前进行初始化,建议放到**Application#onCreate()**。
19 | ```
20 | val options = ShineOptions.Builder()
21 | .setLogEnable(true)
22 | .setLogTag("FreddyChen")
23 | .setBaseUrl("https://api.oick.cn/")
24 | .setParserCls(CustomParser1::class)
25 | .build()
26 | ShineKit.init(options)
27 | ```
28 | 当然,初始化不是强制的,**ShineOptions**会有对应的默认值,默认值可参考*参数及API说明#ShineOptions*
29 |
30 | 3. 使用
31 | ```
32 | suspend fun fetchCatList(): ArrayList {
33 | val options = RequestOptions.Builder()
34 | .setRequestMethod(RequestMethod.GET)
35 | .setBaseUrl("https://cat-fact.herokuapp.com/")
36 | .setFunction("facts/random?amount=2&animal_type=cat")
37 | .build()
38 |
39 | val type = object : TypeToken>() {}.type
40 | return ShineKit.getRequestManager().request(
41 | options = options,
42 | type = type,
43 | parserCls = CustomParser1::class
44 | )
45 | }
46 | ```
47 | 当然,**Type**及**Parser**参数传递我们可以利用**Kotlin**特性封装一个通用的请求方法,这些大家根据自己的业务情况来选择就好,下面提供一个示例:
48 | ```
49 | /**
50 | * 异步请求
51 | */
52 | suspend inline fun request(
53 | requestMethod: RequestMethod,
54 | baseUrl: String = "https://api.oick.cn/",
55 | function: String,
56 | headers: ArrayMap? = null,
57 | params: ArrayMap? = null,
58 | contentType: String = NetworkConfig.DEFAULT_CONTENT_TYPE,
59 | parserCls: KClass = CustomParser1::class,
60 | cipherCls: KClass? = null
61 | ): T {
62 | val optionsBuilder = RequestOptions.Builder()
63 | .setRequestMethod(requestMethod)
64 | .setBaseUrl(baseUrl)
65 | .setFunction(function)
66 | .setContentType(contentType)
67 |
68 | if (!headers.isNullOrEmpty()) {
69 | optionsBuilder.setHeaders(headers)
70 | }
71 |
72 | if (!params.isNullOrEmpty()) {
73 | optionsBuilder.setParams(params)
74 | }
75 |
76 | return ShineKit.getRequestManager()
77 | .request(optionsBuilder.build(), object : TypeToken() {}.type, parserCls, cipherCls)
78 | }
79 | ````
80 | 这样的话,上面的请求可以简化为:
81 | ```
82 | suspend fun fetchCatList(): ArrayList {
83 | return request(
84 | requestMethod = RequestMethod.GET,
85 | baseUrl = "https://cat-fact.herokuapp.com/",
86 | function = "facts/random?amount=2&animal_type=cat",
87 | )
88 | }
89 | ```
90 |
91 | 4. 示例
92 | * 获取历史列表数据
93 | | 服务器域名 | 接口地址 | 参数 | 返回数据结构 | 备注 |
94 | | -- | -- | -- | -- | -- |
95 | | https://api.oick.cn/ | lishi/api.php | / | code、day、result | / |
96 |
97 | 例:
98 | ```
99 | {
100 | "code":"1",
101 | "day":"01/ 17",
102 | "result":[
103 | {
104 | "date":"395年01月17日",
105 | "title":"罗马帝国分裂为西罗马帝国和东罗马帝国"
106 | }
107 | ]
108 | }
109 | ```
110 | 调用方式:
111 | ```
112 | suspend fun fetchHistoryList(): ArrayList {
113 | return request(
114 | requestMethod = RequestMethod.POST,
115 | function = "lishi/api.php",
116 | )
117 | }
118 | ```
119 |
120 | * 获取新闻列表数据
121 | | 服务器域名 | 接口地址 | 参数 | 返回数据结构 | 备注 |
122 | | -- | -- | -- | -- | -- |
123 | | https://is.snssdk.com/ | api/news/feed/v51/ | / | message、data | / |
124 |
125 | 例:
126 | ```
127 | {
128 | "message":"success",
129 | "data":[
130 | {
131 | "content":"test"
132 | }
133 | ]
134 | }
135 | ```
136 | 调用方式:
137 | ```
138 | suspend fun fetchJournalismList(): ArrayList {
139 | return request(
140 | requestMethod = RequestMethod.GET,
141 | baseUrl = "https://is.snssdk.com/",
142 | function = "api/news/feed/v51/",
143 | parserCls = CustomParser2::class,
144 | )
145 | }
146 |
147 | ```
148 | *Note:如有业务需求使用同步请求方式,只需要把`request()`方法改成`syncRequest()`方法即可*。
149 |
150 | ## 版本记录
151 |
152 | | 版本号 | 修改时间 | 版本说明 |
153 | | -- | -- | -- |
154 | | 0.0.7 | 2022.01.16 | 首次提交 |
155 | | 0.0.8 | 2022.02.15 | 修改minSdkVersion为19 |
156 |
157 | ## 免费开放的Api
158 | 提供两个免费开放Api平台给大家,方便测试:
159 | * [红花会 / 免费的api接口](https://gitee.com/safflower_club/free_api_interface#https://gitee.com/link?target=https%3A%2F%2Fwww.free-api.com%2Fdoc%2F533)
160 | * [public-apis](https://github.com/public-apis/public-apis)
161 |
162 | # License
163 |
164 |
165 | Copyright 2022, chenshichao
166 |
167 | Licensed under the Apache License, Version 2.0 (the "License");
168 | you may not use this file except in compliance with the License.
169 | You may obtain a copy of the License at
170 |
171 | http://www.apache.org/licenses/LICENSE-2.0
172 |
173 | Unless required by applicable law or agreed to in writing, software
174 | distributed under the License is distributed on an "AS IS" BASIS,
175 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
176 | See the License for the specific language governing permissions and
177 | limitations under the License.
178 |
179 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/shine-kotlin/src/main/java/com/freddy/shine/kotlin/retrofit/manager/RetrofitRequestManager.kt:
--------------------------------------------------------------------------------
1 | package com.freddy.shine.kotlin.retrofit.manager
2 |
3 | import android.util.ArrayMap
4 | import com.freddy.shine.kotlin.AbstractRequestManager
5 | import com.freddy.shine.kotlin.cipher.ICipher
6 | import com.freddy.shine.kotlin.exception.RequestException
7 | import com.freddy.shine.kotlin.config.RequestMethod
8 | import com.freddy.shine.kotlin.config.RequestOptions
9 | import com.freddy.shine.kotlin.parser.IParser
10 | import com.freddy.shine.kotlin.retrofit.api.IApiService
11 | import com.freddy.shine.kotlin.utils.ShineLog
12 | import okhttp3.MediaType.Companion.toMediaTypeOrNull
13 | import okhttp3.RequestBody
14 | import okhttp3.RequestBody.Companion.toRequestBody
15 | import retrofit2.HttpException
16 | import java.lang.reflect.Type
17 | import kotlin.reflect.KClass
18 |
19 | /**
20 | * 基于Retrofit实现的RequestManager
21 | * @author: FreddyChen
22 | * @date : 2022/01/07 13:50
23 | * @email : freddychencsc@gmail.com
24 | */
25 | internal class RetrofitRequestManager private constructor() : AbstractRequestManager() {
26 |
27 | companion object {
28 | val INSTANCE: RetrofitRequestManager by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
29 | RetrofitRequestManager()
30 | }
31 | }
32 |
33 | /**
34 | * 异步请求
35 | * @param options 请求参数
36 | * @param type 数据类型映射
37 | * @param parserCls 数据解析器
38 | * @param parserCls 数据加解密器
39 | */
40 | override suspend fun request(
41 | options: RequestOptions,
42 | type: Type,
43 | parserCls: KClass,
44 | cipherCls: KClass?
45 | ): T {
46 | ShineLog.d(log = "${javaClass.simpleName}#request()\noptions = $options\ntype = $type\nparserCls = $parserCls\ncipherCls = $cipherCls")
47 | val function = options.function
48 | if (function.isNullOrEmpty()) {
49 | throw RequestException(
50 | type = RequestException.Type.NATIVE,
51 | errMsg = "${javaClass.simpleName}#request failure, reason: function is null or empty"
52 | )
53 | }
54 | val baseUrl = options.baseUrl
55 | if (baseUrl.isNullOrEmpty()) {
56 | throw RequestException(
57 | type = RequestException.Type.NATIVE,
58 | errMsg = "${javaClass.simpleName}#request failure, reason: baseUrl is null or empty"
59 | )
60 | }
61 | val url = "${options.baseUrl}${options.function}"
62 | return try {
63 | val apiService =
64 | RetrofitManager.INSTANCE.getRetrofit(baseUrl)
65 | .create(IApiService::class.java)
66 | val headers = options.headers
67 | RetrofitManager.INSTANCE.saveHeaders("${baseUrl}${function}", headers)
68 |
69 | cipherCls?.apply {
70 | RetrofitManager.INSTANCE.saveCipher("${baseUrl}${function}", this)
71 | }
72 | val params = options.params
73 | val contentType = options.contentType
74 | val result = when (options.requestMethod) {
75 | RequestMethod.GET -> {
76 | if (params.isNullOrEmpty()) {
77 | apiService.get(function)
78 | } else {
79 | apiService.get(function, params)
80 | }
81 | }
82 | RequestMethod.POST -> {
83 | if (params.isNullOrEmpty()) {
84 | apiService.post(function)
85 | } else {
86 | apiService.post(function, convertParamsToRequestBody(params, contentType))
87 | }
88 | }
89 | RequestMethod.PUT -> {
90 | if (params.isNullOrEmpty()) {
91 | apiService.put(function)
92 | } else {
93 | apiService.put(function, convertParamsToRequestBody(params, contentType))
94 | }
95 | }
96 | RequestMethod.DELETE -> {
97 | if (params.isNullOrEmpty()) {
98 | apiService.delete(function)
99 | } else {
100 | apiService.delete(function, params)
101 | }
102 | }
103 | }
104 | parse(url, result, type, parserCls)
105 | } catch (e: HttpException) {
106 | val response = e.response()
107 | val errorBody = response?.errorBody()?.string()
108 | val statusCode = response?.code()
109 | val errorMsg = response?.message()
110 | throw RequestException(
111 | type = RequestException.Type.NETWORK,
112 | url = url,
113 | statusCode = statusCode,
114 | errMsg = errorMsg ?: e.message(),
115 | errBody = errorBody
116 | )
117 | } catch (e: Exception) {
118 | e.printStackTrace()
119 | throw RequestException(
120 | type = RequestException.Type.NATIVE,
121 | url = url,
122 | errMsg = e.message ?: ""
123 | )
124 | }
125 | }
126 |
127 | /**
128 | * 同步请求
129 | * @param options 请求参数
130 | * @param type 数据类型映射
131 | * @param parserCls 数据解析器
132 | * @param cipherCls 数据加解密器
133 | */
134 | override fun syncRequest(
135 | options: RequestOptions,
136 | type: Type,
137 | parserCls: KClass,
138 | cipherCls: KClass?
139 | ): T {
140 | ShineLog.d(log = "${javaClass.simpleName}#syncRequest()\noptions = $options\ntype = $type\nparserCls = $parserCls\ncipherCls = $cipherCls")
141 | val function = options.function
142 | if (function.isNullOrEmpty()) {
143 | throw RequestException(
144 | type = RequestException.Type.NATIVE,
145 | errMsg = "${javaClass.simpleName}#syncRequest failure, reason: function is null or empty"
146 | )
147 | }
148 | val baseUrl = options.baseUrl
149 | if (baseUrl.isNullOrEmpty()) {
150 | throw RequestException(
151 | type = RequestException.Type.NATIVE,
152 | errMsg = "${javaClass.simpleName}#syncRequest failure, reason: baseUrl is null or empty"
153 | )
154 | }
155 | val url = "${options.baseUrl}${options.function}"
156 | return try {
157 | val apiService =
158 | RetrofitManager.INSTANCE.getRetrofit(baseUrl)
159 | .create(IApiService::class.java)
160 | val headers = options.headers
161 | RetrofitManager.INSTANCE.saveHeaders("${baseUrl}${function}", headers)
162 | val params = options.params
163 | val contentType = options.contentType
164 | val result = when (options.requestMethod) {
165 | RequestMethod.GET -> {
166 | if (params.isNullOrEmpty()) {
167 | apiService.syncGet(function)
168 | } else {
169 | apiService.syncGet(function, params)
170 | }
171 | }
172 | RequestMethod.POST -> {
173 | if (params.isNullOrEmpty()) {
174 | apiService.syncPost(function)
175 | } else {
176 | apiService.syncPost(
177 | function,
178 | convertParamsToRequestBody(params, contentType)
179 | )
180 | }
181 | }
182 | RequestMethod.PUT -> {
183 | if (params.isNullOrEmpty()) {
184 | apiService.syncPut(function)
185 | } else {
186 | apiService.syncPut(
187 | function,
188 | convertParamsToRequestBody(params, contentType)
189 | )
190 | }
191 | }
192 | RequestMethod.DELETE -> {
193 | if (params.isNullOrEmpty()) {
194 | apiService.syncDelete(function)
195 | } else {
196 | apiService.syncDelete(
197 | function,
198 | params
199 | )
200 | }
201 | }
202 | }
203 | parse(url, result.execute().body()!!, type, parserCls)
204 | } catch (e: HttpException) {
205 | e.printStackTrace()
206 | val response = e.response()
207 | val errorBody = response?.errorBody()?.string()
208 | val statusCode = response?.code()
209 | val errorMsg = response?.message()
210 | throw RequestException(
211 | type = RequestException.Type.NETWORK,
212 | url = url,
213 | statusCode = statusCode,
214 | errMsg = errorMsg ?: e.message(),
215 | errBody = errorBody
216 | )
217 | } catch (e: Exception) {
218 | e.printStackTrace()
219 | throw RequestException(
220 | type = RequestException.Type.NATIVE,
221 | url = url,
222 | errMsg = e.message ?: ""
223 | )
224 | }
225 | }
226 |
227 | /**
228 | * 将请求参数转换到RequestBody
229 | * POST/PUT请求适用
230 | */
231 | private fun convertParamsToRequestBody(
232 | params: ArrayMap?,
233 | contentType: String
234 | ): RequestBody {
235 | return gson.toJson(params).toRequestBody(contentType.toMediaTypeOrNull())
236 | }
237 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------