├── RxHttp
├── .gitignore
├── src
│ └── main
│ │ ├── AndroidManifest.xml
│ │ ├── res
│ │ └── values
│ │ │ └── strings.xml
│ │ └── java
│ │ └── io
│ │ └── github
│ │ └── kongpf8848
│ │ └── rxhttp
│ │ ├── callback
│ │ ├── ProgressCallback.kt
│ │ ├── DownloadCallback.kt
│ │ └── HttpCallback.kt
│ │ ├── typebuilder
│ │ ├── exception
│ │ │ └── TypeException.kt
│ │ ├── TypeToken.kt
│ │ ├── TypeBuilder.kt
│ │ └── typeimpl
│ │ │ └── ParameterizedTypeImpl.kt
│ │ ├── converter
│ │ ├── IConverter.kt
│ │ ├── GsonConverter.kt
│ │ └── DownloadConverter.kt
│ │ ├── request
│ │ ├── PutRequest.kt
│ │ ├── DeleteRequest.kt
│ │ ├── GetRequest.kt
│ │ ├── PostFormRequest.kt
│ │ ├── DownloadRequest.kt
│ │ ├── PostRequest.kt
│ │ ├── AbsRequest.kt
│ │ └── UploadRequest.kt
│ │ ├── bean
│ │ └── DownloadInfo.kt
│ │ ├── util
│ │ ├── TypeUtil.kt
│ │ ├── GsonUtil.kt
│ │ ├── Md5Util.kt
│ │ └── SSLUtil.kt
│ │ ├── interceptors
│ │ ├── CurlLoggingInterceptor.kt
│ │ └── GzipRequestInterceptor.kt
│ │ ├── HttpConstants.kt
│ │ ├── ByteArrayRequestBody.kt
│ │ ├── RetryWithDelay.kt
│ │ ├── curl
│ │ ├── CurlPrinter.kt
│ │ └── CurlCommandParser.kt
│ │ ├── utf8.kt
│ │ ├── RxHttpTagManager.kt
│ │ ├── Platform.kt
│ │ ├── HttpObserver.kt
│ │ ├── ProgressRequestBody.kt
│ │ ├── ProgressResponseBody.kt
│ │ ├── HttpService.kt
│ │ ├── RxHttpConfig.kt
│ │ └── RxHttp.kt
├── proguard-rules.pro
└── build.gradle
├── app
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ ├── avatar_default.png
│ │ │ ├── cover_default.png
│ │ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ ├── xml
│ │ │ ├── file_paths.xml
│ │ │ └── network_security_config.xml
│ │ ├── values
│ │ │ ├── colors.xml
│ │ │ ├── styles.xml
│ │ │ └── strings.xml
│ │ ├── mipmap-anydpi-v26
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ ├── layout
│ │ │ ├── activity_zhihu.xml
│ │ │ ├── activity_glide.xml
│ │ │ ├── activity_main.xml
│ │ │ ├── activity_mvc.xml
│ │ │ └── activity_mvvm.xml
│ │ ├── drawable-v24
│ │ │ └── ic_launcher_foreground.xml
│ │ └── drawable
│ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ └── io
│ │ │ └── github
│ │ │ └── kongpf8848
│ │ │ └── rxhttp
│ │ │ └── sample
│ │ │ ├── http
│ │ │ ├── TKEmpty.kt
│ │ │ ├── exception
│ │ │ │ ├── NullResponseException.kt
│ │ │ │ └── ServerException.kt
│ │ │ ├── TKResponse.kt
│ │ │ ├── TKURL.kt
│ │ │ ├── interceptor
│ │ │ │ └── MockInterceptor.kt
│ │ │ └── TKErrorCode.kt
│ │ │ ├── bean
│ │ │ ├── User.kt
│ │ │ ├── Banner.kt
│ │ │ └── Feed.kt
│ │ │ ├── utils
│ │ │ ├── GsonUtils.kt
│ │ │ ├── MockUtils.kt
│ │ │ ├── ApkUtils.kt
│ │ │ ├── AssetUtils.kt
│ │ │ └── LogUtils.kt
│ │ │ ├── mvvm
│ │ │ ├── BaseViewModel.kt
│ │ │ ├── MvvmHttpCallback.kt
│ │ │ ├── IBaseMvvm.kt
│ │ │ ├── BaseMvvmActivity.kt
│ │ │ ├── BaseMvvmFragment.kt
│ │ │ ├── TKState.kt
│ │ │ └── NetworkRepository.kt
│ │ │ ├── extension
│ │ │ ├── ActivityExtension.kt
│ │ │ └── LiveDataExtension.kt
│ │ │ ├── image
│ │ │ ├── OkHttpGlideModule.kt
│ │ │ └── transfrom
│ │ │ │ └── RoundCornerTransform.java
│ │ │ ├── activity
│ │ │ ├── GlideActivity.kt
│ │ │ ├── MainActivity.kt
│ │ │ ├── ZhiHuActivity.kt
│ │ │ ├── ZhiHuJavaActivity.java
│ │ │ ├── MVVMActivity.kt
│ │ │ └── MVCActivity.kt
│ │ │ ├── mvc
│ │ │ ├── MVCHttpCallback.kt
│ │ │ └── MVCApi.kt
│ │ │ ├── base
│ │ │ ├── BaseActivity.kt
│ │ │ └── BaseFragment.kt
│ │ │ ├── MyApplication.kt
│ │ │ ├── viewmodel
│ │ │ └── MainViewModel.kt
│ │ │ └── service
│ │ │ └── DownloadService.kt
│ │ └── AndroidManifest.xml
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
└── gradle-mvn-push.gradle
├── .idea
├── encodings.xml
├── codeStyles
│ ├── codeStyleConfig.xml
│ └── Project.xml
├── vcs.xml
├── compiler.xml
├── kotlinc.xml
├── AndroidProjectSystem.xml
├── migrations.xml
├── deploymentTargetSelector.xml
├── misc.xml
├── runConfigurations.xml
├── gradle.xml
├── jarRepositories.xml
├── appInsightsSettings.xml
├── markdown-navigator-enh.xml
└── markdown-navigator.xml
├── .gitignore
├── gradle.properties
├── gradlew.bat
└── gradlew
/RxHttp/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name="RxHttp"
2 | include ':app', ':RxHttp'
3 |
--------------------------------------------------------------------------------
/RxHttp/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/RxHttp/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | RxHttp
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kongpf8848/RxHttp/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kongpf8848/RxHttp/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kongpf8848/RxHttp/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kongpf8848/RxHttp/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/http/TKEmpty.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.http
2 |
3 | class TKEmpty {
4 | }
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kongpf8848/RxHttp/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kongpf8848/RxHttp/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kongpf8848/RxHttp/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kongpf8848/RxHttp/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/avatar_default.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kongpf8848/RxHttp/HEAD/app/src/main/res/mipmap-xxhdpi/avatar_default.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/cover_default.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kongpf8848/RxHttp/HEAD/app/src/main/res/mipmap-xxhdpi/cover_default.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kongpf8848/RxHttp/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kongpf8848/RxHttp/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kongpf8848/RxHttp/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/bean/User.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.bean
2 |
3 | data class User(var uuid: String, var name: String? = null,var address:String?=null)
--------------------------------------------------------------------------------
/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/file_paths.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/callback/ProgressCallback.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.callback
2 |
3 | interface ProgressCallback {
4 | fun onProgress(readBytes: Long, totalBytes: Long)
5 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/typebuilder/exception/TypeException.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.typebuilder.exception
2 |
3 | class TypeException(message: String?) : RuntimeException(message)
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/http/exception/NullResponseException.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.http.exception
2 |
3 | class NullResponseException(val code: Int, val msg: String?) : RuntimeException(msg)
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/http/exception/ServerException.kt:
--------------------------------------------------------------------------------
1 | package com.jsy.tk.library.http.exception
2 |
3 | /**
4 | * 服务器返回的异常
5 | */
6 | class ServerException(val code: Int, val msg: String?) : RuntimeException(msg)
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/callback/DownloadCallback.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.callback
2 |
3 | import io.github.kongpf8848.rxhttp.bean.DownloadInfo
4 |
5 | abstract class DownloadCallback : HttpCallback()
--------------------------------------------------------------------------------
/.idea/AndroidProjectSystem.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/.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 | /buildSrc/build/
15 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Jun 30 10:32:38 GMT+08:00 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-all.zip
7 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/converter/IConverter.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.converter
2 |
3 | import okhttp3.ResponseBody
4 | import java.lang.reflect.Type
5 |
6 | interface IConverter {
7 | @Throws(Exception::class)
8 | fun convert(body: ResponseBody, type: Type): T
9 | }
--------------------------------------------------------------------------------
/.idea/migrations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/bean/Banner.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.bean
2 |
3 | import java.io.Serializable
4 |
5 | data class Banner(
6 | var id: Int,
7 | var pic: String,
8 | var url: String,
9 | var title: String? = null
10 | ) : Serializable
11 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/http/TKResponse.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.http
2 |
3 | import java.io.Serializable
4 |
5 | class TKResponse(val code:Int,val msg: String?, val data: T?) : Serializable {
6 | companion object{
7 | const val STATUS_OK=200
8 | }
9 | fun isSuccess():Boolean{
10 | return code== STATUS_OK
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/network_security_config.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/request/PutRequest.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.request
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import androidx.fragment.app.Fragment
6 |
7 | class PutRequest : PostRequest {
8 | constructor(context: Context) : super(context)
9 | constructor(activity: Activity) : super(activity)
10 | constructor(fragment: Fragment) : super(fragment)
11 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/bean/DownloadInfo.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.bean
2 |
3 | import java.io.Serializable
4 |
5 | class DownloadInfo(var url: String, var dir: String, var fileName: String,var total: Long = 0, var progress: Long = 0):Serializable {
6 |
7 | override fun toString(): String {
8 | return "DownloadInfo(url='$url', dir='$dir', fileName='$fileName', total=$total, progress=$progress)"
9 | }
10 |
11 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/utils/GsonUtils.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.utils
2 |
3 | import android.text.TextUtils
4 | import com.google.gson.Gson
5 |
6 | object GsonUtils {
7 |
8 | private val gson = Gson()
9 |
10 | fun toJson(obj: Any?): String {
11 | var gsonString = ""
12 | if (obj != null && !TextUtils.isEmpty(obj.toString())) {
13 | gsonString = gson.toJson(obj)
14 | }
15 | return gsonString
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.idea/deploymentTargetSelector.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/mvvm/BaseViewModel.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.mvvm
2 |
3 | import android.app.Application
4 | import android.content.Context
5 | import androidx.lifecycle.AndroidViewModel
6 |
7 | /**
8 | * MVVM架构ViewModel基类
9 | */
10 | open class BaseViewModel(application: Application) : AndroidViewModel(application) {
11 |
12 | protected val networkbaseRepository: NetworkRepository = NetworkRepository.instance
13 | protected var context: Context = application.applicationContext
14 |
15 |
16 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/request/DeleteRequest.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.request
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import androidx.fragment.app.Fragment
6 | import okhttp3.RequestBody
7 |
8 | class DeleteRequest : AbsRequest {
9 | constructor(context: Context) : super(context)
10 | constructor(fragment: Fragment) : super(fragment)
11 | constructor(activity: Activity) : super(activity)
12 |
13 | override fun buildRequestBody(): RequestBody? {
14 | return null
15 | }
16 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/util/TypeUtil.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.util
2 |
3 | import java.lang.reflect.ParameterizedType
4 | import java.lang.reflect.Type
5 |
6 | object TypeUtil {
7 |
8 | fun getType(subclass: Class<*>): Type {
9 | val superclass = subclass.genericSuperclass
10 | return if (superclass is Class<*>) {
11 | subclass
12 | } else {
13 | val parameterized = superclass as ParameterizedType
14 | parameterized.actualTypeArguments[0]
15 | }
16 | }
17 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/interceptors/CurlLoggingInterceptor.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.interceptors
2 |
3 | import io.github.kongpf8848.rxhttp.curl.CurlCommandParser
4 | import okhttp3.Interceptor
5 | import okhttp3.Response
6 |
7 | class CurlLoggingInterceptor(var tag: String? = null) : Interceptor {
8 |
9 | override fun intercept(chain: Interceptor.Chain): Response {
10 | val request = chain.request()
11 | CurlCommandParser(tag).parse(request)
12 | return chain.proceed(request)
13 | }
14 |
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/request/GetRequest.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.request
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import androidx.fragment.app.Fragment
6 | import okhttp3.RequestBody
7 |
8 | class GetRequest : AbsRequest {
9 | constructor(context: Context) : super(context)
10 | constructor(activity: Activity) : super(activity)
11 | constructor(fragment: Fragment) : super(fragment)
12 |
13 | public override fun buildRequestBody(): RequestBody? {
14 | return null
15 | }
16 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/request/PostFormRequest.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.request
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import androidx.fragment.app.Fragment
6 | import okhttp3.RequestBody
7 |
8 | class PostFormRequest : AbsRequest {
9 | constructor(context: Context) : super(context)
10 | constructor(activity: Activity) : super(activity)
11 | constructor(fragment: Fragment) : super(fragment)
12 |
13 | public override fun buildRequestBody(): RequestBody? {
14 | return null
15 | }
16 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/util/GsonUtil.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.util
2 |
3 | import android.text.TextUtils
4 | import com.google.gson.Gson
5 | import java.lang.reflect.Type
6 |
7 | object GsonUtil {
8 |
9 | private val gson = Gson()
10 |
11 | fun toJson(obj: Any?): String {
12 | var gsonString = ""
13 | if (obj != null && !TextUtils.isEmpty(obj.toString())) {
14 | gsonString = gson.toJson(obj)
15 | }
16 | return gsonString
17 | }
18 |
19 | fun fromJson(str:String,type: Type):T=gson.fromJson(str,type)
20 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/typebuilder/TypeToken.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.typebuilder
2 |
3 | import io.github.kongpf8848.rxhttp.typebuilder.exception.TypeException
4 | import java.lang.reflect.ParameterizedType
5 | import java.lang.reflect.Type
6 |
7 | abstract class TypeToken {
8 |
9 | val type: Type
10 |
11 | init {
12 | val superclass = javaClass.genericSuperclass
13 | if (superclass is Class<*>) {
14 | throw TypeException("No generics found!")
15 | }
16 | val type = superclass as ParameterizedType
17 | this.type = type.actualTypeArguments[0]
18 | }
19 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/extension/ActivityExtension.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.extension
2 |
3 | import android.net.Uri
4 | import androidx.activity.ComponentActivity
5 | import androidx.activity.result.ActivityResultCallback
6 | import androidx.activity.result.contract.ActivityResultContracts
7 |
8 |
9 | /**
10 | * 获取内容
11 | */
12 | fun ComponentActivity.getContent(input: String, callback: ((uri: Uri) -> Unit)? = null) {
13 | registerForActivityResult(ActivityResultContracts.GetContent(), ActivityResultCallback {
14 | if (it != null && it.toString().isNotEmpty()) {
15 | callback?.invoke(it)
16 | }
17 | }).launch(input)
18 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/extension/LiveDataExtension.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.extension
2 |
3 | import androidx.lifecycle.LifecycleOwner
4 | import androidx.lifecycle.LiveData
5 | import androidx.lifecycle.Observer
6 | import io.github.kongpf8848.rxhttp.sample.mvvm.TKState
7 |
8 | fun LiveData>.observeState(lifecycleOwner: LifecycleOwner, callback: TKState.HandleCallback.() -> Unit) {
9 | this.observe(lifecycleOwner, Observer {
10 | it.handle(callback)
11 | })
12 | }
13 |
14 | fun LiveData>.observeStateForever(callback: TKState.HandleCallback.() -> Unit) {
15 | this.observeForever {
16 | it.handle(callback)
17 | }
18 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/HttpConstants.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp
2 |
3 | object HttpConstants {
4 | const val TIME_OUT = 60L
5 | const val MIME_TYPE_BINARY = "application/octet-stream"
6 | const val MIME_TYPE_TEXT = "text/plain; charset=utf-8"
7 | const val MIME_TYPE_JSON = "application/json; charset=utf-8"
8 | const val MIME_TYPE_PROTOBUF = "application/x-protobuf"
9 | const val MIME_TYPE_APK = "application/vnd.android.package-archive"
10 | const val MIME_TYPE_JPG = "image/jpeg"
11 | const val MIME_TYPE_PNG = "image/png"
12 | const val TEXT_PLAIN="text/plain"
13 | const val APPLICATION_JSON="application/json"
14 | const val APPLICATION_XML="application/xml"
15 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/mvvm/MvvmHttpCallback.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.mvvm
2 |
3 | import io.github.kongpf8848.rxhttp.sample.http.TKResponse
4 | import io.github.kongpf8848.rxhttp.typebuilder.TypeBuilder
5 | import io.github.kongpf8848.rxhttp.util.TypeUtil
6 | import java.lang.reflect.Type
7 |
8 | abstract class MvvmHttpCallback() {
9 |
10 | private val type: Type
11 | init {
12 | val arg = TypeUtil.getType(javaClass)
13 | type = TypeBuilder
14 | .newInstance(TKResponse::class.java)
15 | .addTypeParam(arg)
16 | .build()
17 | }
18 |
19 | fun getType(): Type {
20 | return this.type
21 | }
22 |
23 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/ByteArrayRequestBody.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp
2 |
3 | import okhttp3.MediaType
4 | import okhttp3.RequestBody
5 | import okio.BufferedSink
6 | import java.io.IOException
7 |
8 | class ByteArrayRequestBody(private val contentType: MediaType?, private val byteArray: ByteArray) : RequestBody() {
9 | override fun contentType(): MediaType? {
10 | return contentType
11 | }
12 |
13 | @Throws(IOException::class)
14 | override fun contentLength(): Long {
15 | return byteArray.size.toLong()
16 | }
17 |
18 | @Throws(IOException::class)
19 | override fun writeTo(sink: BufferedSink) {
20 | sink.write(byteArray, 0, byteArray.size)
21 | }
22 |
23 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/converter/GsonConverter.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.converter
2 |
3 | import com.google.gson.JsonSyntaxException
4 | import io.github.kongpf8848.rxhttp.util.GsonUtil
5 | import okhttp3.ResponseBody
6 | import java.lang.reflect.Type
7 |
8 | class GsonConverter : IConverter {
9 |
10 | @Throws(Exception::class)
11 | override fun convert(body: ResponseBody, type: Type): T {
12 | var response: T? = null
13 | val result = body.string()
14 | body.close()
15 | try {
16 | response = GsonUtil.fromJson(result,type) as T
17 | } catch (e: JsonSyntaxException) {
18 | e.printStackTrace()
19 | throw e
20 | }
21 |
22 | return response
23 | }
24 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/http/TKURL.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.http
2 |
3 | object TKURL {
4 |
5 | const val BASE_URL_LOCAL = "http://192.168.12.155:8080/webtest/"
6 | const val URL_GET = BASE_URL_LOCAL + "testGet"
7 | const val URL_POST = BASE_URL_LOCAL + "testPost"
8 | const val URL_POST_FORM = BASE_URL_LOCAL + "testPostForm"
9 | const val URL_PUT = BASE_URL_LOCAL + "testPut"
10 | const val URL_DELETE = BASE_URL_LOCAL + "testDelete"
11 | const val URL_UPLOAD = BASE_URL_LOCAL + "testUpload"
12 | const val URL_DOWNLOAD = "http://hbfile.huabanimg.com/android/huaban-android.apk"
13 | const val URL_DOWNLOAD_2 = "http://image.vcapp.cn/image/apk/JuziBrowser_release_1.6.9.1009_100.apk"
14 | const val URL_ZHIHU = "https://news-at.zhihu.com/api/4/stories/latest"
15 | }
--------------------------------------------------------------------------------
/RxHttp/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
22 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/RetryWithDelay.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp
2 |
3 | import io.reactivex.Observable
4 | import io.reactivex.ObservableSource
5 | import io.reactivex.functions.Function
6 | import java.util.concurrent.TimeUnit
7 |
8 | class RetryWithDelay(private val maxRetries: Int, private val retryDelayMillis: Long) : Function, ObservableSource<*>> {
9 | private var retryCount = 0
10 |
11 | @Throws(Exception::class)
12 | override fun apply(throwableObservable: Observable): ObservableSource<*> {
13 | return throwableObservable.flatMap { throwable ->
14 | if (++retryCount <= maxRetries) {
15 | Observable.timer(retryDelayMillis, TimeUnit.MILLISECONDS)
16 | } else Observable.error(throwable)
17 | }
18 | }
19 |
20 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/curl/CurlPrinter.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.curl
2 |
3 | import android.util.Log
4 |
5 | object CurlPrinter {
6 |
7 | private const val SINGLE_DIVIDER = "────────────────────────────────────────────"
8 |
9 | private const val DEFAULT_TAG = "CURL"
10 |
11 | fun print(tag: String?, url: String, msg: String?) {
12 | val printTag = tag ?: DEFAULT_TAG
13 | val logMsg = StringBuilder("\n")
14 | logMsg.append("\n")
15 | logMsg.append("URL: $url")
16 | logMsg.append("\n")
17 | logMsg.append(SINGLE_DIVIDER)
18 | logMsg.append("\n")
19 | logMsg.append(msg)
20 | logMsg.append("\n")
21 | logMsg.append(SINGLE_DIVIDER)
22 | logMsg.append("\n")
23 | Log.d(printTag, logMsg.toString())
24 | }
25 |
26 | }
--------------------------------------------------------------------------------
/gradle/gradle-mvn-push.gradle:
--------------------------------------------------------------------------------
1 | mavenPublishing {
2 | publishToMavenCentral(true)
3 |
4 | signAllPublications()
5 |
6 | coordinates(GROUP, ARTIFACT_ID, VERSION_NAME)
7 |
8 | pom {
9 | name = POM_NAME
10 | description = POM_DESCRIPTION
11 | inceptionYear = POM_INCEPTION_YEAR
12 | url = POM_URL
13 | licenses {
14 | license {
15 | name = POM_LICENCE_NAME
16 | url = POM_LICENCE_URL
17 | distribution = POM_LICENCE_URL
18 | }
19 | }
20 | developers {
21 | developer {
22 | id = POM_DEVELOPER_ID
23 | name = POM_DEVELOPER_NAME
24 | url = POM_DEVELOPER_URL
25 | }
26 | }
27 | scm {
28 | url = POM_SCM_URL
29 | connection = POM_SCM_CONNECTION
30 | developerConnection = POM_SCM_DEVELOPER_CONNECTION
31 | }
32 | }
33 | }
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/image/OkHttpGlideModule.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.image
2 |
3 | import android.content.Context
4 | import com.bumptech.glide.Glide
5 | import com.bumptech.glide.Registry
6 | import com.bumptech.glide.annotation.GlideModule
7 | import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
8 | import com.bumptech.glide.load.model.GlideUrl
9 | import com.bumptech.glide.module.AppGlideModule
10 | import io.github.kongpf8848.rxhttp.RxHttp
11 | import java.io.InputStream
12 |
13 | @GlideModule
14 | class OkHttpGlideModule : AppGlideModule() {
15 | override fun registerComponents(
16 | context: Context,
17 | glide: Glide,
18 | registry: Registry
19 | ) {
20 | registry.replace(
21 | GlideUrl::class.java,
22 | InputStream::class.java,
23 | OkHttpUrlLoader.Factory(RxHttp.getInstance().getOkHttpClient())
24 | )
25 | }
26 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/callback/HttpCallback.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.callback
2 |
3 | import io.github.kongpf8848.rxhttp.util.TypeUtil
4 | import java.lang.reflect.Type
5 |
6 | abstract class HttpCallback {
7 |
8 | var type: Type
9 |
10 | constructor() {
11 | type = TypeUtil.getType(javaClass)
12 | }
13 |
14 | constructor(type: Type) {
15 | this.type = type
16 | }
17 |
18 | /**
19 | * http请求开始时回调
20 | */
21 | open fun onStart(){}
22 |
23 | /**
24 | * http请求成功时回调
25 | */
26 | abstract fun onNext(response: T?)
27 |
28 | /**
29 | * http请求失败时回调
30 | */
31 | abstract fun onError(e: Throwable?)
32 |
33 | /**
34 | * http请求完成时回调
35 | */
36 | open fun onComplete(){}
37 |
38 | /**
39 | * 上传下载进度回调
40 | * @param readBytes
41 | * @param totalBytes
42 | */
43 | open fun onProgress(readBytes: Long, totalBytes: Long){}
44 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/bean/Feed.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.bean
2 |
3 | import java.io.Serializable
4 |
5 | data class Feed(
6 | var date: String,
7 | var stories: List? = null,
8 | var top_stories: List? = null
9 | ) : Serializable
10 |
11 | data class Story(
12 | var id: Long = 0L,
13 | var type: Int = 0,
14 | var title: String? = null,
15 | var url: String? = null,
16 | var images: List? = null,
17 | var hint: String? = null,
18 | var ga_prefix: String? = null,
19 | var image_hue: String? = null
20 | ) : Serializable
21 |
22 | data class TopStory(
23 | var id: Long = 0L,
24 | var type: Int = 0,
25 | var title: String? = null,
26 | var url: String? = null,
27 | var image: String? = null,
28 | var hint: String? = null,
29 | var ga_prefix: String? = null,
30 | var image_hue: String? = null
31 | ) : Serializable
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/utf8.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp
2 |
3 | import okio.Buffer
4 | import java.io.EOFException
5 |
6 | /**
7 | * Returns true if the body in question probably contains human readable text. Uses a small
8 | * sample of code points to detect unicode control characters commonly used in binary file
9 | * signatures.
10 | */
11 | fun Buffer.isProbablyUtf8(): Boolean {
12 | try {
13 | val prefix = Buffer()
14 | val byteCount = size.coerceAtMost(64)
15 | copyTo(prefix, 0, byteCount)
16 | for (i in 0 until 16) {
17 | if (prefix.exhausted()) {
18 | break
19 | }
20 | val codePoint = prefix.readUtf8CodePoint()
21 | if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
22 | return false
23 | }
24 | }
25 | return true
26 | } catch (_: EOFException) {
27 | return false // Truncated UTF-8 sequence.
28 | }
29 | }
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/util/Md5Util.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.util
2 |
3 | import okio.ByteString.Companion.encodeUtf8
4 | import okio.ByteString.Companion.toByteString
5 | import okio.buffer
6 | import okio.source
7 | import java.io.File
8 | import java.security.MessageDigest
9 |
10 | object Md5Util {
11 |
12 | fun getMD5(str: String) = str.encodeUtf8().md5().hex()
13 |
14 | fun getMD5(file: File?): String? {
15 | var hash: String? = null
16 | if (file == null || !file.exists()) {
17 | return hash
18 | }
19 | val messageDigest = MessageDigest.getInstance("MD5")
20 | file.source().buffer().use {
21 | val buffer = ByteArray(1024)
22 | var len = -1
23 | while (it.read(buffer, 0, buffer.size).also { len = it } != -1) {
24 | messageDigest.update(buffer, 0, len)
25 | }
26 | }
27 | hash = messageDigest.digest().toByteString().hex()
28 | return hash
29 | }
30 |
31 |
32 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/utils/MockUtils.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.utils
2 |
3 | import io.github.kongpf8848.rxhttp.sample.bean.Banner
4 | import io.github.kongpf8848.rxhttp.sample.bean.User
5 | import io.github.kongpf8848.rxhttp.sample.http.TKResponse
6 | import java.util.*
7 |
8 | object MockUtils {
9 |
10 | /**
11 | * 获取轮播图数据
12 | */
13 | fun getBannerData():String {
14 | val list= listOf(
15 | Banner(1, "http://t8.baidu.com/it/u=198337120,441348595&fm=79&app=86&f=JPEG?w=1280&h=732", "https://www.baidu.com", "我是轮播图_1"),
16 | Banner(2, "http://t8.baidu.com/it/u=1484500186,1503043093&fm=79&app=86&f=JPEG?w=1280&h=853", "https://www.qq.com", "我是轮播图_2")
17 | )
18 | val response= TKResponse(200,"",list)
19 | return GsonUtils.toJson(response)
20 | }
21 |
22 | /**
23 | * 获取用户信息
24 | */
25 | fun getUserData():String {
26 | val user= User(UUID.randomUUID().toString(),"feifei","beijing")
27 | val response= TKResponse(200,"",user)
28 | return GsonUtils.toJson(response)
29 | }
30 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/mvvm/IBaseMvvm.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.mvvm
2 |
3 | import android.content.Context
4 | import android.util.Log
5 | import java.lang.reflect.ParameterizedType
6 | import java.lang.reflect.Type
7 |
8 | interface IBaseMvvm {
9 |
10 | fun findType(type: Type): Type? {
11 | return when (type) {
12 | is ParameterizedType -> type
13 | is Class<*> -> {
14 | findType(type.genericSuperclass)
15 | }
16 |
17 | else -> {
18 | null
19 | }
20 | }
21 | }
22 |
23 | fun getLayoutId(context: Context, type: Type): Int {
24 | val name = type.toString()
25 | .substringAfterLast('.') // 提取类名(如 "MainActivityBinding")
26 | .removeSuffix("Binding") // 移除结尾的 Binding
27 | .replace(Regex("(?<=.)([A-Z])"), "_$1")// 驼峰转下划线(如 "Main_Activity")
28 | .lowercase()
29 | Log.d("JACK88", "name:${name},type:$type")
30 | return context.resources.getIdentifier(name, "layout", context.packageName)
31 |
32 | }
33 |
34 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_zhihu.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
12 |
13 |
14 |
21 |
22 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/activity/GlideActivity.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.activity
2 |
3 | import android.os.Bundle
4 | import android.os.Looper
5 | import androidx.databinding.DataBindingUtil
6 | import io.github.kongpf8848.rxhttp.sample.R
7 | import io.github.kongpf8848.rxhttp.sample.base.BaseActivity
8 | import io.github.kongpf8848.rxhttp.sample.databinding.ActivityGlideBinding
9 | import io.github.kongpf8848.rxhttp.sample.image.ImageLoader
10 |
11 |
12 | class GlideActivity : BaseActivity() {
13 | override fun onCreate(savedInstanceState: Bundle?) {
14 | super.onCreate(savedInstanceState)
15 | val binding = DataBindingUtil.setContentView(this, R.layout.activity_glide)
16 | binding.lifecycleOwner = this
17 | Looper.myQueue().addIdleHandler {
18 | ImageLoader.getInstance().load(this@GlideActivity,"http://t8.baidu.com/it/u=198337120,441348595&fm=79&app=86&f=JPEG?w=1280&h=732",binding.ivPic1 )
19 | ImageLoader.getInstance().load(this@GlideActivity,"http://t8.baidu.com/it/u=1484500186,1503043093&fm=79&app=86&f=JPEG?w=1280&h=853",binding.ivPic2)
20 | false
21 | }
22 | }
23 |
24 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/request/DownloadRequest.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.request
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import androidx.fragment.app.Fragment
6 | import okhttp3.RequestBody
7 |
8 | class DownloadRequest : AbsRequest {
9 | var dir: String = ""
10 | var filename: String = ""
11 | var md5: String? = null
12 | var isBreakpoint = false
13 |
14 | constructor(context: Context) : super(context) {}
15 | constructor(activity: Activity) : super(activity) {}
16 | constructor(fragment: Fragment) : super(fragment) {}
17 |
18 | fun dir(dir: String): DownloadRequest {
19 | this.dir = dir
20 | return this
21 | }
22 |
23 | fun filename(filename: String): DownloadRequest {
24 | this.filename = filename
25 | return this
26 | }
27 |
28 | fun breakpoint(breakpoint: Boolean): DownloadRequest {
29 | isBreakpoint = breakpoint
30 | return this
31 | }
32 |
33 | fun md5(md5: String?): DownloadRequest {
34 | this.md5 = md5
35 | return this
36 | }
37 |
38 | override fun buildRequestBody(): RequestBody? {
39 | return null
40 | }
41 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/request/PostRequest.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.request
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import android.text.TextUtils
6 | import androidx.fragment.app.Fragment
7 | import io.github.kongpf8848.rxhttp.HttpConstants
8 | import io.github.kongpf8848.rxhttp.util.GsonUtil
9 | import okhttp3.MediaType.Companion.toMediaTypeOrNull
10 | import okhttp3.RequestBody
11 | import okhttp3.RequestBody.Companion.toRequestBody
12 |
13 | open class PostRequest: AbsRequest {
14 |
15 | private var type: String? = null
16 |
17 | constructor(context: Context) : super(context)
18 | constructor(activity: Activity) : super(activity)
19 | constructor(fragment: Fragment) : super(fragment)
20 |
21 | fun type(type: String): PostRequest {
22 | this.type = type
23 | return this
24 | }
25 |
26 | public override fun buildRequestBody(): RequestBody? {
27 | val content = GsonUtil.toJson(getParams())
28 | return if (TextUtils.isEmpty(type)) {
29 | content.toRequestBody(HttpConstants.MIME_TYPE_JSON.toMediaTypeOrNull())
30 | } else {
31 | content.toRequestBody(type!!.toMediaTypeOrNull())
32 | }
33 | }
34 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/mvc/MVCHttpCallback.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.mvc
2 |
3 | import io.github.kongpf8848.rxhttp.sample.http.TKResponse
4 | import io.github.kongpf8848.rxhttp.typebuilder.TypeBuilder
5 | import io.github.kongpf8848.rxhttp.util.TypeUtil
6 | import java.lang.reflect.Type
7 |
8 | abstract class MVCHttpCallback {
9 |
10 | private val type: Type
11 |
12 | init {
13 | val arg = TypeUtil.getType(javaClass)
14 | type = TypeBuilder
15 | .newInstance(TKResponse::class.java)
16 | .addTypeParam(arg)
17 | .build()
18 | }
19 |
20 | fun getType(): Type {
21 | return this.type
22 | }
23 |
24 | /**
25 | * 请求开始时回调,可以在此加载loading对话框等,默认为空实现
26 | */
27 | open fun onStart() {}
28 | /**
29 | * 抽象方法,请求成功回调,返回内容为对应的数据模型
30 | */
31 | abstract fun onSuccess(result: T?)
32 |
33 | /**
34 | * 抽象方法,请求失败回调,返回内容为code(错误码),msg(错误信息)
35 | */
36 | abstract fun onFailure(code: Int, msg: String?)
37 |
38 | /**
39 | * 上传进度回调,默认为空实现
40 | */
41 | open fun onProgress(readBytes: Long, totalBytes: Long) {}
42 |
43 | /**
44 | * 请求完成时回调,请求成功之后才会回调此方法,默认为空实现
45 | */
46 | open fun onComplete() {}
47 |
48 | }
--------------------------------------------------------------------------------
/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
22 | # okhttp
23 | -dontwarn javax.annotation.**
24 |
25 | # A resource is loaded with a relative path so the package of this class must be preserved.
26 | # -keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
27 |
28 | # Animal Sniffer compileOnly dependency to ensure APIs are compatible with older versions of Java.
29 | -dontwarn org.codehaus.mojo.animal_sniffer.*
30 |
31 | # OkHttp platform used only on JVM and when Conscrypt dependency is available.
32 | -dontwarn okhttp3.internal.platform.ConscryptPlatform
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/activity/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.activity
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import io.github.kongpf8848.rxhttp.sample.R
6 | import io.github.kongpf8848.rxhttp.sample.databinding.ActivityMainBinding
7 | import io.github.kongpf8848.rxhttp.sample.mvvm.BaseMvvmActivity
8 | import io.github.kongpf8848.rxhttp.sample.viewmodel.MainViewModel
9 |
10 |
11 | class MainActivity : BaseMvvmActivity() {
12 |
13 | override fun onCreateEnd(savedInstanceState: Bundle?) {
14 | super.onCreateEnd(savedInstanceState)
15 |
16 | binding.button1.setOnClickListener {
17 | startActivity(Intent(this,MVVMActivity::class.java))
18 | }
19 | binding.button2.setOnClickListener {
20 | startActivity(Intent(this,MVCActivity::class.java))
21 | }
22 |
23 | binding.button3.setOnClickListener {
24 | startActivity(Intent(this,ZhiHuActivity::class.java))
25 | }
26 |
27 | binding.button4.setOnClickListener {
28 | startActivity(Intent(this,ZhiHuJavaActivity::class.java))
29 | }
30 |
31 | binding.button5.setOnClickListener {
32 | startActivity(Intent(this,GlideActivity::class.java))
33 | }
34 |
35 | }
36 |
37 |
38 | }
39 |
40 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/interceptors/GzipRequestInterceptor.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.interceptors
2 |
3 | import okhttp3.Interceptor
4 | import okhttp3.MediaType
5 | import okhttp3.RequestBody
6 | import okhttp3.Response
7 | import okio.BufferedSink
8 | import okio.GzipSink
9 | import okio.buffer
10 |
11 | class GzipRequestInterceptor : Interceptor {
12 |
13 | override fun intercept(chain: Interceptor.Chain): Response {
14 | val originRequest = chain.request()
15 | if (originRequest.body == null || originRequest.header("Content-Encoding") != null) {
16 | return chain.proceed(originRequest);
17 | }
18 | val newRequest = originRequest.newBuilder().header("Content-Encoding", "gzip")
19 | .method(originRequest.method, gzip(originRequest.body!!))
20 | .build()
21 | return chain.proceed(newRequest)
22 | }
23 |
24 | private fun gzip(body: RequestBody) = object : RequestBody() {
25 |
26 | override fun contentType(): MediaType? {
27 | return body.contentType()
28 | }
29 |
30 | override fun contentLength(): Long {
31 | return -1
32 | }
33 |
34 | override fun writeTo(sink: BufferedSink) {
35 | val gzipSink = GzipSink(sink).buffer()
36 | body.writeTo(gzipSink)
37 | gzipSink.close()
38 | }
39 |
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_glide.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
12 |
13 |
14 |
21 |
22 |
28 |
29 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/RxHttpTagManager.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp
2 |
3 | import io.reactivex.disposables.Disposable
4 | import java.util.*
5 | import java.util.concurrent.ConcurrentHashMap
6 |
7 | class RxHttpTagManager private constructor(){
8 |
9 | private object RxHttpTagManager {
10 | val holder = RxHttpTagManager()
11 | }
12 |
13 | private val map: MutableMap = ConcurrentHashMap(16)
14 |
15 | fun addTag(tag: Any?, disposable: Disposable) {
16 | if (tag != null) {
17 | this.map[tag] = disposable
18 | }
19 | }
20 |
21 | fun removeTag(tag: Any?) {
22 | if (tag != null) {
23 | map.remove(tag)
24 | }
25 | }
26 |
27 | fun cancelTag(tag: Any?) {
28 | if (tag != null) {
29 | if (map.containsKey(tag)) {
30 | dispose(map[tag])
31 | removeTag(tag)
32 | }
33 | } else {
34 | for ((_, value) in map) {
35 | dispose(value)
36 | }
37 | map.clear()
38 | }
39 | }
40 |
41 | private fun dispose(disposable: Disposable?) {
42 | if (disposable != null && !disposable.isDisposed) {
43 | disposable.dispose()
44 | }
45 | }
46 |
47 | companion object {
48 | fun getInstance()=RxHttpTagManager.holder
49 |
50 | fun generateRandomTag(): String {
51 | return UUID.randomUUID().toString()
52 | }
53 | }
54 | }
--------------------------------------------------------------------------------
/RxHttp/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'kotlin-android'
4 | id 'kotlin-parcelize'
5 | id 'kotlin-kapt'
6 | id "com.vanniktech.maven.publish" version "0.34.0"
7 | }
8 | android {
9 | namespace 'io.github.kongpf8848.rxhttp'
10 | compileSdk Config.compileSdkVersion
11 |
12 | defaultConfig {
13 | minSdk Config.minSdkVersion
14 | targetSdk Config.targetSdkVersion
15 | }
16 |
17 | buildTypes {
18 |
19 | release {
20 | minifyEnabled false
21 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
22 | }
23 | }
24 |
25 | compileOptions {
26 | sourceCompatibility Config.sourceCompatibilityVersion
27 | targetCompatibility Config.targetCompatibilityVersion
28 | }
29 |
30 | kotlinOptions {
31 | jvmTarget = "17"
32 | }
33 |
34 | lint {
35 | abortOnError false
36 | }
37 |
38 |
39 | }
40 |
41 | dependencies {
42 |
43 | implementation fileTree(dir: "libs", include: ["*.jar"])
44 | implementation AndroidX.appCompat
45 | testImplementation BuildDependencies.junit
46 | api BuildDependencies.rxjava2
47 | api BuildDependencies.rxAndroid
48 | api BuildDependencies.retrofit
49 | api BuildDependencies.okhttp
50 | api BuildDependencies.retrofitConverterScalars
51 | api BuildDependencies.retrofitConverterGson
52 | api BuildDependencies.retrofitAdapterRxjava2
53 | api BuildDependencies.autodispose
54 | }
55 |
56 | apply from: rootProject.file('gradle/gradle-mvn-push.gradle')
--------------------------------------------------------------------------------
/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | RxHttp
3 |
4 | MVVM架构使用RxHttp示例(kotlin)
5 | MVC架构使用RxHttp示例(kotlin)
6 | 知乎日报API(kotlin)
7 | 知乎日报API(java)
8 | Glide和网络请求公用OkHttpClient
9 |
10 | 最新文章
11 |
12 | GET请求
13 | POST请求
14 | POST FORM请求
15 | PUT请求
16 | DELETE请求
17 | 上传(需要和后台服务端协作)
18 | 下载
19 |
20 | 权限申请
21 | 确定
22 | 取消
23 | %1$s需要%2$s权限,去设置?
24 |
25 | 下载进度:%d%%
26 | 下载失败
27 | 下载完成
28 |
29 | 亲,可在Logcat查看输出日志,搜索关键字OkHttp即可,响应数据为模拟数据,通过添加拦截器MockInterceptor模拟服务器返回数据,
30 | 此处假设服务器返回的数据格式为{"code":200,"data":T,"msg":\" \"},code为响应码,data对应的数据类型为泛型,基本数据类型(boolean,int,double...),String,{ },[ ]都是支持的
31 | 亲,可在Logcat查看输出日志,搜索关键字OkHttp即可
32 |
33 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/Platform.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp
2 |
3 | import android.os.Build
4 | import android.os.Handler
5 | import android.os.Looper
6 | import java.util.concurrent.Executor
7 | import java.util.concurrent.Executors
8 |
9 | open class Platform {
10 | open fun defaultCallbackExecutor(): Executor? {
11 | return null
12 | }
13 |
14 | internal class Java : Platform() {
15 | override fun defaultCallbackExecutor(): Executor? {
16 | return Executor { command -> Executors.newCachedThreadPool().execute(command) }
17 | }
18 | }
19 |
20 | internal class Android : Platform() {
21 | override fun defaultCallbackExecutor(): Executor? {
22 | return MainThreadExecutor()
23 | }
24 |
25 | internal class MainThreadExecutor : Executor {
26 | private val handler = Handler(Looper.getMainLooper())
27 | override fun execute(r: Runnable) {
28 | handler.post(r)
29 | }
30 | }
31 | }
32 |
33 | companion object {
34 | private val PLATFORM = findPlatform()
35 | fun get(): Platform {
36 | return PLATFORM
37 | }
38 |
39 | private fun findPlatform(): Platform {
40 | try {
41 | Class.forName("android.os.Build")
42 | if (Build.VERSION.SDK_INT != 0) {
43 | return Android()
44 | }
45 | } catch (ignored: ClassNotFoundException) {
46 | }
47 | return Java()
48 | }
49 | }
50 | }
--------------------------------------------------------------------------------
/.idea/appInsightsSettings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/HttpObserver.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp
2 |
3 | import androidx.annotation.NonNull
4 | import io.github.kongpf8848.rxhttp.callback.HttpCallback
5 | import io.reactivex.Observer
6 | import io.reactivex.disposables.Disposable
7 | import io.reactivex.internal.disposables.DisposableHelper
8 | import io.reactivex.internal.util.EndConsumerHelper
9 | import java.util.concurrent.atomic.AtomicReference
10 |
11 | class HttpObserver(private val callback: HttpCallback?, private val tag: Any?) : Observer, Disposable {
12 |
13 | private val upstream = AtomicReference()
14 |
15 | override fun onSubscribe(@NonNull d: Disposable) {
16 | if (EndConsumerHelper.setOnce(upstream, d, javaClass)) {
17 | if (tag != null) {
18 | RxHttpTagManager.getInstance().addTag(tag, d)
19 | }
20 | onStart()
21 | }
22 | }
23 |
24 | override fun isDisposed(): Boolean {
25 | return upstream.get() === DisposableHelper.DISPOSED
26 | }
27 |
28 | override fun dispose() {
29 | if (tag != null) {
30 | RxHttpTagManager.getInstance().removeTag(tag)
31 | }
32 | DisposableHelper.dispose(upstream)
33 | }
34 |
35 | private fun onStart() {
36 | callback?.onStart()
37 | }
38 |
39 | override fun onNext(response: T) {
40 | callback?.onNext(response)
41 | }
42 |
43 | override fun onError(e: Throwable) {
44 | callback?.onError(e)
45 | dispose()
46 | }
47 |
48 | override fun onComplete() {
49 | callback?.onComplete()
50 | dispose()
51 | }
52 |
53 | companion object {
54 | private const val TAG = "HttpObserver"
55 | }
56 |
57 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/utils/ApkUtils.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.utils
2 |
3 | import android.content.Context
4 | import android.content.Intent
5 | import android.net.Uri
6 | import android.os.Build
7 | import androidx.core.content.FileProvider
8 | import java.io.File
9 |
10 | object ApkUtils {
11 |
12 | /**
13 | * 安装Apk
14 | */
15 | fun installApk(context: Context, file: File?, authority: String) {
16 | if (file == null || !file.exists()) {
17 | return
18 | }
19 | try {
20 | // val pm = context.packageManager
21 | // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
22 | // if (!pm.canRequestPackageInstalls()) {
23 | // val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + context.packageName))
24 | // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
25 | // context.startActivity(intent)
26 | // return
27 | // }
28 | // }
29 | val intent = Intent(Intent.ACTION_VIEW)
30 | val uri: Uri
31 | uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
32 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
33 | FileProvider.getUriForFile(context, authority, file)
34 | } else {
35 | Uri.fromFile(file)
36 | }
37 | intent.setDataAndType(uri, "application/vnd.android.package-archive")
38 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
39 | context.startActivity(intent)
40 | } catch (e: Exception) {
41 | e.printStackTrace()
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/typebuilder/TypeBuilder.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.typebuilder
2 |
3 | import io.github.kongpf8848.rxhttp.typebuilder.exception.TypeException
4 | import io.github.kongpf8848.rxhttp.typebuilder.typeimpl.ParameterizedTypeImpl
5 | import java.lang.reflect.Type
6 | import java.util.*
7 |
8 | class TypeBuilder private constructor(val raw: Class<*>, val parent: TypeBuilder?) {
9 |
10 | private val args = ArrayList()
11 |
12 | companion object {
13 | fun newInstance(raw: Class<*>): TypeBuilder {
14 | return TypeBuilder(raw, null)
15 | }
16 | private fun newInstance(raw: Class<*>, parent: TypeBuilder): TypeBuilder {
17 | return TypeBuilder(raw, parent)
18 | }
19 | }
20 |
21 | fun beginSubType(raw: Class<*>): TypeBuilder {
22 | return newInstance(raw, this)
23 | }
24 |
25 | fun endSubType(): TypeBuilder {
26 | if (parent == null) {
27 | throw TypeException("expect beginSubType() before endSubType()")
28 | }
29 | parent.addTypeParam(type)
30 | return parent
31 | }
32 |
33 | fun addTypeParam(clazz: Class<*>?): TypeBuilder {
34 | return addTypeParam(clazz as Type?)
35 | }
36 |
37 | fun addTypeParam(type: Type?): TypeBuilder {
38 | if (type == null) {
39 | throw NullPointerException("addTypeParam expect not null Type")
40 | }
41 | args.add(type)
42 | return this
43 | }
44 |
45 | fun build(): Type {
46 | if (parent != null) {
47 | throw TypeException("expect endSubType() before build()")
48 | }
49 | return type
50 | }
51 |
52 | private val type: Type
53 | get() = if (args.isEmpty()) {
54 | raw
55 | } else ParameterizedTypeImpl(raw, args.toTypedArray(), null)
56 |
57 |
58 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/http/interceptor/MockInterceptor.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.http.interceptor
2 |
3 | import io.github.kongpf8848.rxhttp.HttpConstants
4 | import io.github.kongpf8848.rxhttp.sample.http.TKURL
5 | import io.github.kongpf8848.rxhttp.sample.utils.MockUtils
6 | import okhttp3.Interceptor
7 | import okhttp3.MediaType.Companion.toMediaTypeOrNull
8 | import okhttp3.Protocol
9 | import okhttp3.Response
10 | import okhttp3.ResponseBody
11 | import java.io.IOException
12 | import java.net.HttpURLConnection
13 |
14 | class MockInterceptor : Interceptor {
15 |
16 | @Throws(IOException::class)
17 | override fun intercept(chain: Interceptor.Chain): Response {
18 | val request = chain.request()
19 | val url = request.url.toString()
20 | val responseBuilder = Response.Builder()
21 | .code(HttpURLConnection.HTTP_OK)
22 | .message("")
23 | .request(request)
24 | .protocol(Protocol.HTTP_1_1)
25 | .addHeader("Content-Type", HttpConstants.MIME_TYPE_JSON)
26 | var responseString=""
27 | return if (url.startsWith(TKURL.URL_GET)) {
28 | responseString = MockUtils.getBannerData()
29 | responseBuilder.body(ResponseBody.create(HttpConstants.MIME_TYPE_JSON.toMediaTypeOrNull(), responseString.toByteArray()))
30 | responseBuilder.build()
31 |
32 | } else if ( TKURL.URL_POST == url || TKURL.URL_POST_FORM == url || TKURL.URL_PUT == url || TKURL.URL_DELETE == url) {
33 | responseString = MockUtils.getUserData()
34 | responseBuilder.body(ResponseBody.create(HttpConstants.MIME_TYPE_JSON.toMediaTypeOrNull(), responseString.toByteArray()))
35 | responseBuilder.build()
36 | }
37 | else {
38 | chain.proceed(request)
39 | }
40 | }
41 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/utils/AssetUtils.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.utils
2 |
3 | import android.content.Context
4 | import java.io.*
5 |
6 | object AssetUtils {
7 |
8 | /**
9 | * 读取assets目录下的文件
10 | */
11 | fun openFile(context: Context,fileName: String):InputStream?{
12 | try{
13 | return context.assets.open(fileName)
14 | }
15 | catch (e:IOException){
16 | e.printStackTrace()
17 | }
18 | return null
19 | }
20 |
21 | /**
22 | * 复制src/main/assets目录下的文件到指定目录
23 | */
24 | fun copyAssets(context: Context, fileName: String, destDirectory: String): Boolean {
25 | var destDir = destDirectory
26 | var `in`: InputStream? = null
27 | var out: OutputStream? = null
28 | try {
29 | `in` = context.resources.assets.open(fileName)
30 | if (!destDir.endsWith(File.separator)) destDir += File.separator
31 | val parent = File(destDir)
32 | if (!parent.exists()) {
33 | parent.mkdirs()
34 | }
35 | out = FileOutputStream(destDir + fileName)
36 | val buffer = ByteArray(1024)
37 | var length: Int
38 | while (`in`.read(buffer).also { length = it } > 0) {
39 | out.write(buffer, 0, length)
40 | }
41 | out.flush()
42 | } catch (e: Exception) {
43 | e.printStackTrace()
44 | return false
45 | } finally {
46 | try {
47 | `in`?.close()
48 | } catch (e: Exception) {
49 | e.printStackTrace()
50 | }
51 | try {
52 | out?.close()
53 | } catch (e: IOException) {
54 | e.printStackTrace()
55 | }
56 | }
57 | return true
58 | }
59 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/activity/ZhiHuActivity.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.activity
2 |
3 | import android.os.Bundle
4 | import android.util.Log
5 | import androidx.databinding.DataBindingUtil
6 | import io.github.kongpf8848.rxhttp.RxHttp
7 | import io.github.kongpf8848.rxhttp.callback.HttpCallback
8 | import io.github.kongpf8848.rxhttp.sample.R
9 | import io.github.kongpf8848.rxhttp.sample.base.BaseActivity
10 | import io.github.kongpf8848.rxhttp.sample.bean.Feed
11 | import io.github.kongpf8848.rxhttp.sample.databinding.ActivityZhihuBinding
12 | import io.github.kongpf8848.rxhttp.sample.http.TKURL
13 |
14 | /**
15 | * 知乎日报API
16 | */
17 | class ZhiHuActivity : BaseActivity() {
18 | override fun onCreate(savedInstanceState: Bundle?) {
19 | super.onCreate(savedInstanceState)
20 | setContentView(R.layout.activity_zhihu)
21 | val binding = DataBindingUtil.setContentView(this, R.layout.activity_zhihu).apply { }
22 | binding.lifecycleOwner = this
23 | binding.button1.setOnClickListener {
24 | RxHttp.getInstance().get(baseActivity).url(TKURL.URL_ZHIHU)
25 | .tag(null)
26 | .enqueue(object : HttpCallback() {
27 | override fun onStart() {
28 | Log.d(TAG, "onStart() called")
29 | }
30 |
31 | override fun onNext(response: Feed?) {
32 | Log.d(TAG, "onNext() called with: response = $response")
33 | }
34 |
35 | override fun onError(e: Throwable?) {
36 | Log.d(TAG, "onError() called with: e = $e")
37 | }
38 |
39 | override fun onComplete() {
40 | Log.d(TAG, "onComplete() called")
41 | }
42 | })
43 | }
44 | }
45 |
46 |
47 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
12 |
13 |
19 |
20 |
26 |
27 |
33 |
34 |
40 |
41 |
47 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/mvvm/BaseMvvmActivity.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.mvvm
2 |
3 | import android.os.Bundle
4 | import androidx.databinding.DataBindingUtil
5 | import androidx.databinding.ViewDataBinding
6 | import androidx.lifecycle.ViewModelProvider
7 | import io.github.kongpf8848.rxhttp.sample.base.BaseActivity
8 | import java.lang.reflect.ParameterizedType
9 | import java.lang.reflect.Type
10 |
11 | /**
12 | * MVVM架构Activity基类
13 | */
14 | abstract class BaseMvvmActivity : BaseActivity(),
15 | IBaseMvvm {
16 |
17 | lateinit var viewModel: VM
18 | lateinit var binding: VDB
19 |
20 |
21 | final override fun onCreate(savedInstanceState: Bundle?) {
22 | onCreateStart(savedInstanceState)
23 | super.onCreate(savedInstanceState)
24 |
25 | binding =
26 | DataBindingUtil.setContentView(this, getLayoutId(applicationContext, viewBindingType()))
27 | binding.lifecycleOwner = this
28 | createViewModel()
29 | onCreateEnd(savedInstanceState)
30 | }
31 |
32 | protected open fun onCreateStart(savedInstanceState: Bundle?) {}
33 | protected open fun onCreateEnd(savedInstanceState: Bundle?) {}
34 |
35 |
36 | /**
37 | * 创建ViewModel
38 | */
39 | private fun createViewModel() {
40 | val type = findType(javaClass.genericSuperclass)
41 | val modelClass = if (type is ParameterizedType) {
42 | type.actualTypeArguments[0] as Class
43 | } else {
44 | BaseViewModel::class.java as Class
45 | }
46 | viewModel = ViewModelProvider(this)[modelClass]
47 | }
48 |
49 | private fun viewBindingType(): Type {
50 | val type = findType(javaClass.genericSuperclass)
51 | return if (type is ParameterizedType) {
52 | type.actualTypeArguments[1] as Class
53 | } else {
54 | ViewDataBinding::class.java as Class
55 | }
56 | }
57 |
58 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/ProgressRequestBody.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp
2 |
3 | import io.github.kongpf8848.rxhttp.callback.ProgressCallback
4 | import okhttp3.MediaType
5 | import okhttp3.RequestBody
6 | import okio.*
7 | import java.io.IOException
8 |
9 | class ProgressRequestBody(private val requestBody: RequestBody, private val callback: ProgressCallback?) : RequestBody() {
10 |
11 | private var progressSink: BufferedSink? = null
12 | private var contentLength = 0L
13 |
14 | override fun contentType(): MediaType? {
15 | return requestBody.contentType()
16 | }
17 |
18 | @Throws(IOException::class)
19 | override fun contentLength(): Long {
20 | if (contentLength == 0L) {
21 | contentLength = requestBody.contentLength()
22 | }
23 | return contentLength
24 | }
25 |
26 | @Throws(IOException::class)
27 | override fun writeTo(sink: BufferedSink) {
28 | if (callback == null) {
29 | requestBody.writeTo(sink)
30 | return
31 | }
32 | if (progressSink == null) {
33 | progressSink = sink(sink).buffer()
34 | }
35 | callback.onProgress(0, contentLength())
36 | requestBody.writeTo(progressSink!!)
37 | progressSink?.apply {
38 | flush()
39 | close()
40 | }
41 | }
42 |
43 | private fun sink(sink: Sink): Sink {
44 | return object : ForwardingSink(sink) {
45 | var totalBytesWrite = 0L
46 | var lastBytesWrite = 0L
47 |
48 | @Throws(IOException::class)
49 | override fun write(source: Buffer, byteCount: Long) {
50 | super.write(source, byteCount)
51 | lastBytesWrite = totalBytesWrite
52 | totalBytesWrite += byteCount
53 | if (totalBytesWrite != lastBytesWrite) {
54 | callback?.onProgress(totalBytesWrite, contentLength())
55 | }
56 | }
57 | }
58 | }
59 |
60 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/ProgressResponseBody.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp
2 |
3 | import io.github.kongpf8848.rxhttp.callback.ProgressCallback
4 | import okhttp3.MediaType
5 | import okhttp3.ResponseBody
6 | import okio.*
7 | import java.io.IOException
8 |
9 | class ProgressResponseBody(private val responseBody: ResponseBody, private val callback: ProgressCallback?) : ResponseBody() {
10 |
11 | private var progressSource: BufferedSource? = null
12 | private var contentLength = 0L
13 |
14 | override fun contentType(): MediaType? {
15 | return responseBody.contentType()
16 | }
17 |
18 | override fun contentLength(): Long {
19 | if (contentLength == 0L) {
20 | contentLength = responseBody.contentLength()
21 | }
22 | return contentLength
23 | }
24 |
25 | override fun source(): BufferedSource {
26 | if (callback == null) {
27 | return responseBody.source()
28 | }
29 | if (progressSource == null) {
30 | progressSource = source(responseBody.source()).buffer()
31 | }
32 | return progressSource!!
33 | }
34 |
35 | private fun source(source: Source): Source {
36 | return object : ForwardingSource(source) {
37 | var totalBytesRead = 0L
38 | var lastBytesRead = 0L
39 |
40 | @Throws(IOException::class)
41 | override fun read(sink: Buffer, byteCount: Long): Long {
42 | val bytesRead = super.read(sink, byteCount)
43 | lastBytesRead = totalBytesRead
44 | totalBytesRead += if (bytesRead != -1L) bytesRead else 0
45 | if (totalBytesRead != lastBytesRead) {
46 | callback?.onProgress(totalBytesRead, contentLength())
47 | }
48 | return bytesRead
49 | }
50 | }
51 | }
52 |
53 | override fun close() {
54 | try {
55 | progressSource?.close()
56 | } catch (e: Exception) {
57 | e.printStackTrace()
58 | }
59 | }
60 |
61 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/base/BaseActivity.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.base
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import androidx.appcompat.app.AppCompatActivity
6 | import io.github.kongpf8848.rxhttp.sample.utils.LogUtils
7 |
8 |
9 | open class BaseActivity : AppCompatActivity() {
10 |
11 | val TAG=javaClass.simpleName
12 |
13 | lateinit var baseActivity: BaseActivity
14 |
15 | override fun onCreate(savedInstanceState: Bundle?) {
16 | super.onCreate(savedInstanceState)
17 | baseActivity=this
18 | LogUtils.d(TAG, "onCreate called")
19 | }
20 |
21 | override fun onStart() {
22 | super.onStart()
23 | LogUtils.d(TAG, "onStart() called")
24 | }
25 |
26 | override fun onResume() {
27 | super.onResume()
28 | LogUtils.d(TAG, "onResume() called")
29 | }
30 |
31 | override fun onPause() {
32 | super.onPause()
33 | LogUtils.d(TAG, "onPause() called")
34 | }
35 |
36 | override fun onStop() {
37 | super.onStop()
38 | LogUtils.d(TAG, "onStop() called")
39 | }
40 |
41 | override fun onDestroy() {
42 | super.onDestroy()
43 | LogUtils.d(TAG, "onDestroy() called")
44 | }
45 |
46 | override fun onRestart() {
47 | super.onRestart()
48 | LogUtils.d(TAG, "onRestart() called")
49 | }
50 |
51 | override fun onContentChanged() {
52 | super.onContentChanged()
53 | LogUtils.d(TAG, "onContentChanged() called")
54 | }
55 |
56 | override fun onNewIntent(intent: Intent) {
57 | super.onNewIntent(intent)
58 | LogUtils.d(TAG, "onNewIntent() called")
59 | }
60 |
61 | override fun onSaveInstanceState(outState: Bundle) {
62 | super.onSaveInstanceState(outState)
63 | LogUtils.d(TAG, "onSaveInstanceState() called")
64 | }
65 |
66 | override fun onRestoreInstanceState(savedInstanceState: Bundle) {
67 | super.onRestoreInstanceState(savedInstanceState)
68 | LogUtils.d(TAG, "onRestoreInstanceState() called")
69 | }
70 |
71 | }
--------------------------------------------------------------------------------
/.idea/markdown-navigator-enh.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/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 | # When configured, Gradle will run in incubating parallel mode.
10 | # This option should only be used with decoupled projects. More details, visit
11 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
12 | # org.gradle.parallel=true
13 | # AndroidX package structure to make it clearer which packages are bundled with the
14 | # Android operating system, and which are packaged with your app's APK
15 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
16 | android.enableJetifier=true
17 | android.useAndroidX=true
18 | org.gradle.jvmargs=-Xmx4096m
19 | org.gradle.parallel=true
20 | android.defaults.buildfeatures.buildconfig=true
21 | android.enableR8.fullMode=false
22 | android.nonFinalResIds=false
23 | android.nonTransitiveRClass=false
24 |
25 | GROUP=io.github.kongpf8848
26 | ARTIFACT_ID=RxHttp
27 | VERSION_NAME=1.1.0
28 |
29 | POM_NAME=RxHttp
30 | POM_DESCRIPTION=Http library base on Retrofit and RxJava2
31 | POM_INCEPTION_YEAR=2025
32 | POM_URL=https://github.com/kongpf8848/RxHttp
33 |
34 | POM_LICENCE_NAME=The Apache License, Version 2.0
35 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
36 |
37 | POM_DEVELOPER_ID=kongpf8848
38 | POM_DEVELOPER_NAME=kongpf8848
39 | POM_DEVELOPER_URL=https://github.com/kongpf8848
40 |
41 | POM_SCM_URL=https://github.com/kongpf8848/RxHttp
42 | POM_SCM_CONNECTION=scm:git:git://github.com/kongpf8848/RxHttp.git
43 | POM_SCM_DEVELOPER_CONNECTION=scm:git:ssh://git@github.com/kongpf8848/RxHttp.git
44 |
45 | mavenCentralUsername=username
46 | mavenCentralPassword=password
47 |
48 | signing.keyId=08BCC212
49 | signing.password=12345678
50 | signing.secretKeyRingFile=/Users/kongpengfei/.gnupg/secring.gpg
51 |
52 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/request/AbsRequest.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.request
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import androidx.fragment.app.Fragment
6 | import io.github.kongpf8848.rxhttp.RxHttp
7 | import io.github.kongpf8848.rxhttp.RxHttpTagManager
8 | import io.github.kongpf8848.rxhttp.callback.HttpCallback
9 | import okhttp3.RequestBody
10 |
11 | abstract class AbsRequest {
12 |
13 | private var context: Any? = null
14 | private var url: String = ""
15 | private var tag: Any? = null
16 | private var param: Map? = null
17 | protected var callback:HttpCallback<*>?=null
18 |
19 | protected abstract fun buildRequestBody(): RequestBody?
20 |
21 | constructor(context: Context) {
22 | this.context = context
23 | }
24 |
25 | constructor(fragment: Fragment) {
26 | context = fragment
27 | }
28 |
29 | constructor(activity: Activity) {
30 | context = activity
31 | }
32 |
33 | fun url(url: String): AbsRequest {
34 | this.url = url
35 | return this
36 | }
37 |
38 | fun tag(tag: Any?): AbsRequest {
39 | this.tag = tag
40 | return this
41 | }
42 |
43 | fun params(params: Map?): AbsRequest {
44 | this.param = params
45 | return this
46 | }
47 |
48 | val actualContext: Context?
49 | get() {
50 | if (context is Context) {
51 | return context as Context
52 | } else if (context is Fragment) {
53 | return (context as Fragment).requireContext()
54 | }
55 | return null
56 | }
57 |
58 | fun getTag(): Any? {
59 | return if (tag == null) {
60 | RxHttpTagManager.generateRandomTag()
61 | } else tag
62 | }
63 |
64 | fun getContext()=context
65 |
66 | fun getUrl()=url
67 |
68 | fun getParams(): Map? {
69 | return param?.filterValues { it!=null }
70 | }
71 |
72 | fun enqueue(callback: HttpCallback) {
73 | this.callback=callback
74 | RxHttp.getInstance().enqueue(this, callback)
75 | }
76 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/activity/ZhiHuJavaActivity.java:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.activity;
2 |
3 | import android.os.Bundle;
4 | import android.util.Log;
5 | import android.widget.Button;
6 |
7 | import org.jetbrains.annotations.Nullable;
8 |
9 | import io.github.kongpf8848.rxhttp.RxHttp;
10 | import io.github.kongpf8848.rxhttp.callback.HttpCallback;
11 | import io.github.kongpf8848.rxhttp.sample.R;
12 | import io.github.kongpf8848.rxhttp.sample.base.BaseActivity;
13 | import io.github.kongpf8848.rxhttp.sample.bean.Feed;
14 | import io.github.kongpf8848.rxhttp.sample.http.TKURL;
15 |
16 | public class ZhiHuJavaActivity extends BaseActivity {
17 | private static final String TAG = "ZhiHuJavaActivity";
18 |
19 | @Override
20 | protected void onCreate(@Nullable Bundle savedInstanceState) {
21 | super.onCreate(savedInstanceState);
22 | setContentView(R.layout.activity_zhihu);
23 |
24 | Button button1 = findViewById(R.id.button1);
25 | button1.setOnClickListener(v -> {
26 | RxHttp.Companion.getInstance().get(baseActivity).url(TKURL.URL_ZHIHU)
27 | .enqueue(new HttpCallback() {
28 |
29 | @Override
30 | public void onStart() {
31 | super.onStart();
32 | Log.d(TAG, "onStart() called");
33 | }
34 |
35 | @Override
36 | public void onError(@Nullable Throwable e) {
37 | Log.d(TAG, "onError() called with: e = [" + e + "]");
38 | }
39 |
40 | @Override
41 | public void onNext(@Nullable Feed response) {
42 | Log.d(TAG, "onNext() called with: response = [" + response + "]");
43 | }
44 |
45 | @Override
46 | public void onComplete() {
47 | super.onComplete();
48 | Log.d(TAG, "onComplete() called");
49 | }
50 | });
51 | });
52 |
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/http/TKErrorCode.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.http
2 |
3 | import com.google.gson.JsonSyntaxException
4 | import com.jsy.tk.library.http.exception.ServerException
5 | import org.json.JSONException
6 | import java.net.ConnectException
7 | import java.net.SocketTimeoutException
8 | import java.net.UnknownHostException
9 | import java.text.ParseException
10 | import javax.net.ssl.SSLHandshakeException
11 |
12 | object TKErrorCode {
13 |
14 | /**
15 | * 未知异常
16 | */
17 | const val ERRCODE_UNKNOWN = -1
18 |
19 | const val ERRCODE_UNKNOWN_DESC="unknown exception"
20 |
21 | /**
22 | * 网络异常
23 | */
24 | const val ERRCODE_NETWORK = -2
25 |
26 | const val ERRCODE_NETWORK_DESC="network exception"
27 |
28 | /**
29 | * 返回数据为null
30 | */
31 | const val ERRCODE_RESPONSE_NULL = -3
32 |
33 | const val ERRCODE_RESPONSE_NULL_DESC="response data is null"
34 |
35 |
36 | /**
37 | * Json转换异常
38 | */
39 | const val ERRCODE_JSON_PARSE = -4
40 |
41 | const val ERRCODE_JSON_PARSE_DESC="response data json parse error"
42 |
43 |
44 | fun handleThrowable(throwable: Throwable?): Pair {
45 | return when (throwable) {
46 | /**
47 | * 网络异常
48 | */
49 | is ConnectException,
50 | is SocketTimeoutException,
51 | is UnknownHostException,
52 | is SSLHandshakeException
53 | -> {
54 | Pair(ERRCODE_NETWORK, throwable.message)
55 | }
56 | /**
57 | * Json异常
58 | */
59 | is JsonSyntaxException,
60 | is JSONException,
61 | is ParseException
62 | -> {
63 | Pair(ERRCODE_JSON_PARSE, throwable.message)
64 | }
65 |
66 | /**
67 | * 服务端返回的异常
68 | */
69 | is ServerException -> {
70 | Pair(throwable.code, throwable.msg)
71 | }
72 |
73 | /**
74 | * 未知异常
75 | */
76 | else -> {
77 | Pair(ERRCODE_UNKNOWN, throwable?.message?: ERRCODE_UNKNOWN_DESC)
78 | }
79 |
80 | }
81 | }
82 |
83 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/mvvm/BaseMvvmFragment.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.mvvm
2 |
3 | import android.os.Bundle
4 | import android.view.LayoutInflater
5 | import android.view.View
6 | import android.view.ViewGroup
7 | import androidx.databinding.DataBindingUtil
8 | import androidx.databinding.ViewDataBinding
9 | import androidx.lifecycle.ViewModelProvider
10 | import io.github.kongpf8848.rxhttp.sample.base.BaseFragment
11 | import java.lang.reflect.ParameterizedType
12 | import java.lang.reflect.Type
13 |
14 | /**
15 | * MVVM架构Fragment基类
16 | */
17 | abstract class BaseMvvmFragment : BaseFragment(),
18 | IBaseMvvm {
19 |
20 | lateinit var viewModel: VM
21 | lateinit var binding: VDB
22 | protected var rootView: View? = null
23 |
24 |
25 | override fun onCreateView(
26 | inflater: LayoutInflater,
27 | container: ViewGroup?,
28 | savedInstanceState: Bundle?
29 | ): View? {
30 | if (rootView == null) {
31 | binding = DataBindingUtil.inflate(
32 | inflater,
33 | getLayoutId(requireContext(), viewBindingType()),
34 | null,
35 | false
36 | )
37 | rootView = binding.root
38 | binding.lifecycleOwner = viewLifecycleOwner
39 | createViewModel()
40 | } else {
41 | val parent = rootView!!.parent as? ViewGroup
42 | parent?.removeView(rootView)
43 | }
44 | return rootView
45 | }
46 |
47 |
48 | private fun createViewModel() {
49 | val type = findType(javaClass.genericSuperclass)
50 | val modelClass = if (type is ParameterizedType) {
51 | type.actualTypeArguments[0] as Class
52 | } else {
53 | BaseViewModel::class.java as Class
54 | }
55 | viewModel = ViewModelProvider(this)[modelClass]
56 | }
57 |
58 | private fun viewBindingType(): Type {
59 | val type = findType(javaClass.genericSuperclass)
60 | return if (type is ParameterizedType) {
61 | type.actualTypeArguments[1] as Class
62 | } else {
63 | ViewDataBinding::class.java as Class
64 | }
65 | }
66 |
67 |
68 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/HttpService.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp
2 |
3 | import io.reactivex.Observable
4 | import okhttp3.RequestBody
5 | import okhttp3.ResponseBody
6 | import retrofit2.Call
7 | import retrofit2.http.*
8 |
9 | interface HttpService {
10 | /**
11 | * GET请求
12 | * @param url
13 | * @return
14 | */
15 | @GET
16 | fun get(@Url url: String): Observable
17 |
18 | @GET
19 | fun get(@Url url: String, @QueryMap map: @JvmSuppressWildcards Map): Observable
20 |
21 | /**
22 | * POST请求
23 | * @param url
24 | * @param body
25 | * @return
26 | */
27 | @POST
28 | fun post(@Url url: String, @Body body: RequestBody): Observable
29 |
30 | /**
31 | * POST表单请求
32 | * @param url
33 | * @param map
34 | * @return
35 | */
36 | @POST
37 | @FormUrlEncoded
38 | fun postForm(@Url url: String): Observable
39 |
40 | @POST
41 | @FormUrlEncoded
42 | fun postForm(@Url url: String, @FieldMap(encoded = true) map: @JvmSuppressWildcards Map): Observable
43 |
44 | /**
45 | * PUT请求
46 | * @param url
47 | * @param body
48 | * @return
49 | */
50 | @PUT
51 | fun put(@Url url: String, @Body body: RequestBody): Observable
52 |
53 | /**
54 | * DELETE请求
55 | * @param url
56 | * @param map
57 | * @return
58 | */
59 | @HTTP(method = "DELETE", hasBody = true)
60 | fun delete(@Url url: String): Observable
61 |
62 | @HTTP(method = "DELETE", hasBody = true)
63 | fun delete(@Url url: String, @Body map: @JvmSuppressWildcards Map): Observable
64 |
65 | /**
66 | * 下载请求
67 | * @param url
68 | * @return
69 | */
70 | @GET
71 | @Streaming
72 | fun download(@Url url: String): Observable
73 |
74 | /**
75 | * 下载请求
76 | * @param url
77 | * @param range
78 | * @return
79 | */
80 | @GET
81 | @Streaming
82 | fun download(@Url url: String, @Header("RANGE") range: String): Observable
83 |
84 | /**
85 | * HEAD请求
86 | * @param url
87 | * @return
88 | */
89 | @HEAD
90 | fun head(@Url url: String): Call
91 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/base/BaseFragment.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.base
2 |
3 | import android.content.Context
4 | import android.os.Bundle
5 | import android.view.View
6 | import androidx.fragment.app.Fragment
7 | import io.github.kongpf8848.rxhttp.sample.utils.LogUtils
8 |
9 |
10 | open class BaseFragment : Fragment() {
11 |
12 | val TAG = javaClass.simpleName
13 |
14 | override fun onAttach(context: Context) {
15 | super.onAttach(context)
16 | LogUtils.d(TAG, "onAttach")
17 | }
18 |
19 | override fun setUserVisibleHint(isVisibleToUser: Boolean) {
20 | super.setUserVisibleHint(isVisibleToUser)
21 | LogUtils.d(TAG, "setUserVisibleHint:$isVisibleToUser")
22 | }
23 |
24 | override fun onHiddenChanged(hidden: Boolean) {
25 | super.onHiddenChanged(hidden)
26 | LogUtils.d(TAG, "onHiddenChanged:$hidden")
27 | }
28 |
29 | override fun onCreate(savedInstanceState: Bundle?) {
30 | super.onCreate(savedInstanceState)
31 | LogUtils.d(TAG, "onCreate")
32 | }
33 |
34 |
35 | override fun onViewCreated(
36 | view: View,
37 | savedInstanceState: Bundle?
38 | ) {
39 | super.onViewCreated(view, savedInstanceState)
40 | LogUtils.d(TAG, "onViewCreated")
41 | }
42 |
43 | override fun onActivityCreated(savedInstanceState: Bundle?) {
44 | super.onActivityCreated(savedInstanceState)
45 | LogUtils.d(TAG, "onActivityCreated")
46 | }
47 |
48 | override fun onStart() {
49 | super.onStart()
50 | LogUtils.d(TAG, "onStart")
51 | }
52 |
53 | override fun onPause() {
54 | super.onPause()
55 | LogUtils.d(TAG, "onPause")
56 | }
57 |
58 | override fun onStop() {
59 | super.onStop()
60 | LogUtils.d(TAG, "onStop")
61 | }
62 |
63 | override fun onResume() {
64 | super.onResume()
65 | LogUtils.d(TAG, "onResume")
66 | }
67 |
68 | override fun onDestroyView() {
69 | super.onDestroyView()
70 | LogUtils.d(TAG, "onDestroyView")
71 | }
72 |
73 | override fun onDestroy() {
74 | super.onDestroy()
75 | LogUtils.d(TAG, "onDestroy")
76 | }
77 |
78 | override fun onDetach() {
79 | super.onDetach()
80 | LogUtils.d(TAG, "onDetach")
81 | }
82 |
83 |
84 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/curl/CurlCommandParser.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.curl
2 |
3 | import android.util.Log
4 | import io.github.kongpf8848.rxhttp.HttpConstants
5 | import okhttp3.Headers
6 | import okhttp3.Request
7 | import okio.Buffer
8 | import java.nio.charset.StandardCharsets.UTF_8
9 |
10 |
11 | class CurlCommandParser(var tag: String? = null) {
12 | private val curlCommandBuilder = StringBuilder();
13 | fun parse(request: Request) {
14 | curlCommandBuilder.append("curl")
15 | curlCommandBuilder.append(" -X ${request.method}")
16 | for ((key, value) in request.headers) {
17 | addHeader(key, value)
18 | }
19 |
20 | val requestBody = request.body
21 | if (requestBody != null) {
22 | val contentType = requestBody.contentType()
23 | if (contentType != null) {
24 | addHeader("Content-Type", contentType.toString())
25 | }
26 | if (bodyHasUnknownEncoding(request.headers)) {
27 | } else if (requestBody.isDuplex()) {
28 | } else if (requestBody.isOneShot()) {
29 | } else {
30 | val buffer = Buffer()
31 | requestBody.writeTo(buffer)
32 | val charset = contentType?.charset(UTF_8) ?: UTF_8
33 | curlCommandBuilder.append(" -d '" + buffer.readString(charset) + "'");
34 | }
35 | }
36 | curlCommandBuilder.append(" \"${request.url}\"")
37 | CurlPrinter.print(tag,"${request.url}", curlCommandBuilder.toString());
38 |
39 | }
40 |
41 | private fun bodyHasUnknownEncoding(headers: Headers): Boolean {
42 | val contentType=headers["Content-Type"]
43 | if (contentType!=null) {
44 | return !(contentType.contains(HttpConstants.TEXT_PLAIN) || contentType.contains(
45 | HttpConstants.APPLICATION_JSON
46 | ) || contentType.contains(HttpConstants.APPLICATION_XML))
47 | }
48 | val contentEncoding = headers["Content-Encoding"] ?: return false
49 | return !contentEncoding.equals("identity", ignoreCase = true) &&
50 | !contentEncoding.equals("gzip", ignoreCase = true)
51 | }
52 |
53 | private fun addHeader(name: String, value: String) {
54 | curlCommandBuilder.append(" -H \"$name: $value\"")
55 | }
56 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/MyApplication.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample
2 |
3 | import android.app.Application
4 | import io.github.kongpf8848.commonhelper.ToastHelper
5 | import io.github.kongpf8848.rxhttp.interceptors.FixHttpLoggingInterceptor
6 | import io.github.kongpf8848.rxhttp.RxHttpConfig
7 | import io.github.kongpf8848.rxhttp.interceptors.CurlLoggingInterceptor
8 | import io.github.kongpf8848.rxhttp.sample.http.interceptor.MockInterceptor
9 | import io.github.kongpf8848.rxhttp.sample.utils.LogUtils
10 | import java.util.concurrent.TimeUnit
11 |
12 |
13 | class MyApplication : Application() {
14 |
15 | override fun onCreate() {
16 | super.onCreate()
17 | Thread.setDefaultUncaughtExceptionHandler { t, e ->
18 | e.printStackTrace()
19 | LogUtils.e("Crash", e.message)
20 | }
21 | LogUtils.init(this, BuildConfig.DEBUG)
22 | ToastHelper.init(this)
23 |
24 | /**
25 | * 对RxHttp进行配置,可选
26 | */
27 | RxHttpConfig.getInstance()
28 | /**
29 | * 失败重试次数
30 | */
31 | .maxRetries(3)
32 | /**
33 | * 每次失败重试间隔时间
34 | */
35 | .retryDelayMillis(200)
36 | /**
37 | * 证书校验,单向校验,即客户端校验服务端证书,null则为不校验
38 | */
39 | //.certificate(AssetUtils.openFile(applicationContext,"xxx.cer"))
40 | /**
41 | * 设置OkHttpClient.Builder(),RxHttp支持自定义OkHttpClient.Builder()
42 | */
43 | .getBuilder().apply {
44 | connectTimeout(60, TimeUnit.SECONDS)
45 | readTimeout(60, TimeUnit.SECONDS)
46 | writeTimeout(60, TimeUnit.SECONDS)
47 | /**
48 | * DEBUG模式下,添加日志拦截器,建议使用RxHttp中的FixHttpLoggingInterceptor,使用OkHttp的HttpLoggingInterceptor在上传下载的时候会有问题
49 | */
50 | if (BuildConfig.DEBUG) {
51 | addInterceptor(FixHttpLoggingInterceptor().apply {
52 | level = FixHttpLoggingInterceptor.Level.BODY
53 | })
54 | addInterceptor(CurlLoggingInterceptor())
55 | addInterceptor(MockInterceptor())
56 | }
57 | }
58 |
59 | }
60 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/request/UploadRequest.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.request
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import android.net.Uri
6 | import androidx.fragment.app.Fragment
7 | import io.github.kongpf8848.rxhttp.ByteArrayRequestBody
8 | import io.github.kongpf8848.rxhttp.HttpConstants
9 | import io.github.kongpf8848.rxhttp.Platform
10 | import io.github.kongpf8848.rxhttp.ProgressRequestBody
11 | import io.github.kongpf8848.rxhttp.callback.ProgressCallback
12 | import okhttp3.MediaType.Companion.toMediaTypeOrNull
13 | import okhttp3.MultipartBody
14 | import okhttp3.RequestBody
15 | import java.io.File
16 | import java.io.IOException
17 |
18 | class UploadRequest : PostRequest {
19 |
20 | constructor(context: Context) : super(context)
21 | constructor(activity: Activity) : super(activity)
22 | constructor(fragment: Fragment) : super(fragment)
23 |
24 | override fun buildRequestBody(): RequestBody? {
25 | val builder = MultipartBody.Builder().setType(MultipartBody.FORM)
26 | val params: Map? = getParams()
27 | if (!params.isNullOrEmpty()) {
28 | for((key,value) in params){
29 | if (value is File) {
30 | builder.addFormDataPart(key, value.name, RequestBody.create(HttpConstants.MIME_TYPE_BINARY.toMediaTypeOrNull(), value))
31 | } else if (value is Uri) {
32 | try {
33 | val inputStream = actualContext!!.contentResolver.openInputStream(value)
34 | if (inputStream != null) {
35 | val bytes = inputStream.readBytes()
36 | inputStream.close()
37 | builder.addFormDataPart(key, key, ByteArrayRequestBody(HttpConstants.MIME_TYPE_BINARY.toMediaTypeOrNull(), bytes))
38 | }
39 | } catch (e: IOException) {
40 | e.printStackTrace()
41 | }
42 | } else {
43 | builder.addFormDataPart(key, value.toString())
44 | }
45 | }
46 | }
47 | return ProgressRequestBody(builder.build(), object : ProgressCallback {
48 | override fun onProgress(readBytes: Long, totalBytes: Long) {
49 | Platform.get().defaultCallbackExecutor()?.execute { callback?.onProgress(readBytes, totalBytes) }
50 | }
51 | })
52 | }
53 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'kotlin-parcelize'
4 | //apply plugin: 'kotlin-kapt'
5 |
6 |
7 | android {
8 | namespace 'io.github.kongpf8848.rxhttp.sample'
9 | compileSdk Config.compileSdkVersion
10 |
11 | defaultConfig {
12 | minSdk Config.minSdkVersion
13 | targetSdk Config.targetSdkVersion
14 | versionCode Config.versionCode
15 | versionName Config.versionName
16 | }
17 | buildTypes {
18 | debug {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | release {
23 | minifyEnabled false
24 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
25 | }
26 | }
27 | compileOptions {
28 | sourceCompatibility Config.sourceCompatibilityVersion
29 | targetCompatibility Config.targetCompatibilityVersion
30 | }
31 |
32 | kotlinOptions {
33 | jvmTarget = "17"
34 | }
35 |
36 | buildFeatures {
37 | dataBinding true
38 | viewBinding true
39 | }
40 | }
41 |
42 | dependencies {
43 | api project(':RxHttp')
44 | implementation fileTree(dir: 'libs', include: ['*.jar'])
45 | api AndroidX.appCompat
46 | api AndroidX.legacyV4
47 | api AndroidX.legacyV13
48 | api AndroidX.multidex
49 | api AndroidX.material
50 | api AndroidX.recyclerview
51 | api AndroidX.preference
52 | api AndroidX.cardview
53 | api AndroidX.gridlayout
54 | api AndroidX.annotationX
55 | api AndroidX.constraintlayout
56 | api AndroidX.paging
57 | api AndroidX.work
58 | api AndroidX.coreKtx
59 | api AndroidX.room
60 | api AndroidX.roomKtx
61 | annotationProcessor(AndroidX.roomCompiler)
62 | api AndroidX.roomRxJava2
63 | api AndroidX.coordinatorlayout
64 | api AndroidX.databindingCommon
65 | api AndroidX.databindingRuntime
66 | api AndroidX.databindingAdapters
67 | api AndroidX.activity
68 | api AndroidX.activityKtx
69 | api AndroidX.fragment
70 | api AndroidX.fragmentKtx
71 | implementation BuildDependencies.kotlinStdlibJdk7
72 | implementation BuildDependencies.gson
73 | implementation BuildDependencies.commonhelper
74 | implementation BuildDependencies.glide
75 | annotationProcessor(BuildDependencies.glideCompiler)
76 | implementation BuildDependencies.glideIntegration
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/converter/DownloadConverter.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.converter
2 |
3 | import io.github.kongpf8848.rxhttp.Platform
4 | import io.github.kongpf8848.rxhttp.ProgressResponseBody
5 | import io.github.kongpf8848.rxhttp.bean.DownloadInfo
6 | import io.github.kongpf8848.rxhttp.callback.DownloadCallback
7 | import io.github.kongpf8848.rxhttp.callback.ProgressCallback
8 | import io.github.kongpf8848.rxhttp.request.DownloadRequest
9 | import okhttp3.ResponseBody
10 | import okio.buffer
11 | import okio.sink
12 | import java.io.File
13 | import java.io.FileOutputStream
14 | import java.lang.reflect.Type
15 |
16 | class DownloadConverter(private val downloadRequest: DownloadRequest, private val callback: DownloadCallback) : IConverter {
17 |
18 | private val downloadInfo= DownloadInfo(downloadRequest.getUrl(), downloadRequest.dir, downloadRequest.filename)
19 |
20 | @Throws(Exception::class)
21 | override fun convert(body: ResponseBody, type: Type): T {
22 | try {
23 | val fileDir = File(downloadInfo.dir)
24 | if (!fileDir.exists()) {
25 | fileDir.mkdirs()
26 | }
27 | val file = File(downloadInfo.dir, downloadInfo.fileName)
28 | val currentProgress= if (downloadRequest.isBreakpoint) {
29 | if (file.exists()) {
30 | file.length()
31 | } else {
32 | 0L
33 | }
34 | } else {
35 | 0L
36 | }
37 | val fos = FileOutputStream(file, downloadRequest.isBreakpoint)
38 | val progressResponseBody = ProgressResponseBody(body, object : ProgressCallback {
39 | override fun onProgress(readBytes: Long, totalBytes: Long) {
40 | downloadInfo.progress=currentProgress+readBytes
41 | Platform.get().defaultCallbackExecutor()!!.execute { callback.onProgress(downloadInfo.progress, currentProgress+totalBytes) }
42 | }
43 | })
44 | downloadInfo.total = currentProgress + progressResponseBody.contentLength()
45 | Platform.get().defaultCallbackExecutor()?.execute { callback.onProgress(currentProgress,downloadInfo.total) }
46 | val sink = fos.sink().buffer()
47 | sink.writeAll(progressResponseBody.source())
48 | sink.flush()
49 | sink.close()
50 | progressResponseBody.close()
51 | } catch (e: Exception) {
52 | throw e
53 | }
54 | return downloadInfo as T
55 | }
56 |
57 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_mvc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
6 |
7 |
11 |
12 |
13 |
21 |
22 |
28 |
29 |
35 |
36 |
42 |
43 |
44 |
50 |
51 |
57 |
58 |
59 |
65 |
66 |
67 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/RxHttpConfig.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp
2 |
3 | import io.github.kongpf8848.rxhttp.util.SSLUtil
4 | import okhttp3.OkHttpClient
5 | import java.io.InputStream
6 | import java.security.KeyManagementException
7 | import java.security.NoSuchAlgorithmException
8 | import java.util.*
9 | import java.util.concurrent.TimeUnit
10 | import javax.net.ssl.HostnameVerifier
11 |
12 | class RxHttpConfig {
13 |
14 | private object Config {
15 | val holder = RxHttpConfig()
16 | }
17 |
18 | var okhttpBuilder: OkHttpClient.Builder? = null
19 | var maxRetries = 0
20 | var retryDelayMillis = 0L
21 | var certificates:MutableList?=null
22 |
23 | private fun defaultBuilder(): OkHttpClient.Builder {
24 | val builder = OkHttpClient.Builder().apply {
25 | connectTimeout(HttpConstants.TIME_OUT, TimeUnit.SECONDS)
26 | readTimeout(HttpConstants.TIME_OUT, TimeUnit.SECONDS)
27 | writeTimeout(HttpConstants.TIME_OUT, TimeUnit.SECONDS)
28 | }
29 | try {
30 | val sslParams= SSLUtil.getSSLSocketFactory(certificates =certificates)
31 | builder.sslSocketFactory(sslParams.first,sslParams.second)
32 | builder.hostnameVerifier(HostnameVerifier { _, _ -> true })
33 | } catch (e: NoSuchAlgorithmException) {
34 | e.printStackTrace()
35 | } catch (e: KeyManagementException) {
36 | e.printStackTrace()
37 | }
38 | return builder
39 | }
40 |
41 | fun builder(builder: OkHttpClient.Builder): RxHttpConfig {
42 | this.okhttpBuilder = builder
43 | return this
44 | }
45 |
46 | fun retryDelayMillis(retryDelayMillis: Long): RxHttpConfig {
47 | this.retryDelayMillis = retryDelayMillis
48 | return this
49 | }
50 |
51 | fun maxRetries(maxRetries: Int): RxHttpConfig {
52 | this.maxRetries = maxRetries
53 | return this
54 | }
55 |
56 | fun certificate(cer:InputStream?):RxHttpConfig{
57 | if(this.certificates==null){
58 | this.certificates=ArrayList()
59 | }
60 | cer?.let {
61 | this.certificates!!.add(it)
62 | }
63 | return this
64 | }
65 |
66 | fun certificates(cerList:List?):RxHttpConfig{
67 | if(this.certificates==null){
68 | this.certificates=ArrayList()
69 | }
70 | cerList?.forEach {
71 | this.certificates!!.add(it)
72 | }
73 | return this
74 | }
75 |
76 | fun getBuilder(): OkHttpClient.Builder {
77 | if (okhttpBuilder == null) {
78 | okhttpBuilder = defaultBuilder()
79 | }
80 | return okhttpBuilder!!
81 | }
82 |
83 | companion object {
84 | fun getInstance() = Config.holder
85 | }
86 | }
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_mvvm.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
12 |
13 |
17 |
18 |
19 |
27 |
28 |
34 |
35 |
41 |
42 |
48 |
49 |
50 |
56 |
57 |
63 |
64 |
65 |
71 |
72 |
73 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
23 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
37 |
38 |
42 |
43 |
47 |
51 |
55 |
56 |
60 |
61 |
66 |
69 |
70 |
71 |
72 |
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/typebuilder/typeimpl/ParameterizedTypeImpl.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.typebuilder.typeimpl
2 |
3 | import io.github.kongpf8848.rxhttp.typebuilder.exception.TypeException
4 | import java.lang.reflect.ParameterizedType
5 | import java.lang.reflect.Type
6 | import java.lang.reflect.TypeVariable
7 | import java.util.*
8 |
9 | class ParameterizedTypeImpl(private val raw: Class<*>, private var args: Array?, private val owner: Type?) : ParameterizedType {
10 |
11 | private fun checkArgs() {
12 |
13 | val typeParameters: Array>> = raw.typeParameters
14 | if (args!!.isNotEmpty() && typeParameters.size != args!!.size) {
15 | throw TypeException(raw.name + " expect " + typeParameters.size + " arg(s), got " + args!!.size)
16 | }
17 | }
18 |
19 | init {
20 | if (args == null){
21 | args=emptyArray()
22 | }
23 | checkArgs()
24 | }
25 |
26 | override fun getActualTypeArguments(): Array? {
27 | return args
28 | }
29 |
30 | override fun getRawType(): Type? {
31 | return raw
32 | }
33 |
34 | override fun getOwnerType(): Type? {
35 | return owner
36 | }
37 |
38 | override fun toString(): String {
39 | val sb = StringBuilder()
40 | sb.append(raw.name)
41 | if (args!!.isNotEmpty()) {
42 | sb.append('<')
43 | for (i in args!!.indices) {
44 | if (i != 0) {
45 | sb.append(", ")
46 | }
47 | val type = args!![i]
48 | if (type is Class<*>) {
49 | var clazz = type as Class<*>
50 | if (clazz.isArray) {
51 | var count = 0
52 | do {
53 | count++
54 | clazz = clazz.componentType!!
55 | } while (clazz.isArray)
56 | sb.append(clazz.name)
57 | for (j in count downTo 1) {
58 | sb.append("[]")
59 | }
60 | } else {
61 | sb.append(clazz.name)
62 | }
63 | } else {
64 | sb.append(args!![i].toString())
65 | }
66 | }
67 | sb.append('>')
68 | }
69 | return sb.toString()
70 | }
71 |
72 | override fun equals(o: Any?): Boolean {
73 | if (this === o) return true
74 | if (o == null || javaClass != o.javaClass) return false
75 | val that = o as ParameterizedTypeImpl
76 | if (raw != that.raw) return false
77 | // Probably incorrect - comparing Object[] arrays with Arrays.equals
78 | if (!Arrays.equals(args, that.args)) return false
79 | return if (owner != null) owner == that.owner else that.owner == null
80 | }
81 |
82 | override fun hashCode(): Int {
83 | var result = raw.hashCode()
84 | result = 31 * result + Arrays.hashCode(args)
85 | result = 31 * result + (owner?.hashCode() ?: 0)
86 | return result
87 | }
88 |
89 |
90 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/viewmodel/MainViewModel.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.viewmodel
2 |
3 | import android.app.Application
4 | import androidx.lifecycle.MutableLiveData
5 | import io.github.kongpf8848.rxhttp.sample.bean.Banner
6 | import io.github.kongpf8848.rxhttp.sample.bean.Feed
7 | import io.github.kongpf8848.rxhttp.sample.bean.User
8 | import io.github.kongpf8848.rxhttp.sample.http.TKURL
9 | import io.github.kongpf8848.rxhttp.sample.mvvm.BaseViewModel
10 | import io.github.kongpf8848.rxhttp.sample.mvvm.TKState
11 | import kotlinx.coroutines.flow.Flow
12 | import kotlinx.coroutines.flow.flow
13 | import retrofit2.Retrofit
14 | import retrofit2.converter.gson.GsonConverterFactory
15 | import retrofit2.http.GET
16 |
17 | class MainViewModel(application: Application) : BaseViewModel(application) {
18 |
19 |
20 | fun testGet(params: Map?): MutableLiveData>> {
21 |
22 | return networkbaseRepository.httpGet(
23 | context = context,
24 | url = TKURL.URL_GET,
25 | params = params
26 | )
27 | }
28 |
29 | fun testPost(params: Map?, tag: Any? = null): MutableLiveData> {
30 | return networkbaseRepository.httpPost(
31 | context = context,
32 | url = TKURL.URL_POST,
33 | params = params,
34 | tag = tag
35 | )
36 | }
37 |
38 | fun testPostForm(params: Map?, tag: Any? = null): MutableLiveData> {
39 | return networkbaseRepository.httpPostForm(
40 | context = context,
41 | url = TKURL.URL_POST_FORM,
42 | params = params,
43 | tag = tag
44 | )
45 | }
46 |
47 | fun testPut(params: Map?, tag: Any? = null): MutableLiveData> {
48 | return networkbaseRepository.httpPut(
49 | context = context,
50 | url = TKURL.URL_PUT,
51 | params = params,
52 | tag = tag
53 | )
54 | }
55 |
56 | fun testDelete(params: Map?, tag: Any? = null): MutableLiveData> {
57 | return networkbaseRepository.httpDelete(
58 | context = context,
59 | url = TKURL.URL_DELETE,
60 | params = params,
61 | tag = tag
62 | )
63 | }
64 |
65 | fun testUpload(params: Map?, tag: Any? = null): MutableLiveData> {
66 | return networkbaseRepository.httpUpload(
67 | context = context,
68 | url = TKURL.URL_UPLOAD,
69 | params = params,
70 | tag = tag
71 | )
72 | }
73 |
74 | interface API {
75 | @GET("api/4/stories/latest")
76 | suspend fun getArticles(): Feed
77 | }
78 |
79 | private fun getArticles(): Flow = flow {
80 | val retrofit = Retrofit.Builder()
81 | .baseUrl("https://news-at.zhihu.com/")
82 | .addConverterFactory(GsonConverterFactory.create())
83 | .build()
84 | val api = retrofit.create(API::class.java)
85 | val feed = api.getArticles()
86 | println("Resume on ${Thread.currentThread().name}")
87 | emit(feed)
88 | }
89 |
90 |
91 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/util/SSLUtil.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.util
2 |
3 | import java.io.IOException
4 | import java.io.InputStream
5 | import java.security.KeyManagementException
6 | import java.security.KeyStore
7 | import java.security.NoSuchAlgorithmException
8 | import java.security.SecureRandom
9 | import java.security.cert.CertificateException
10 | import java.security.cert.CertificateFactory
11 | import java.security.cert.X509Certificate
12 | import javax.net.ssl.*
13 |
14 | object SSLUtil {
15 |
16 | private val UnSafeTrustManager: X509TrustManager = object : X509TrustManager {
17 | @Throws(CertificateException::class)
18 | override fun checkClientTrusted(chain: Array, authType: String) {
19 | }
20 |
21 | @Throws(CertificateException::class)
22 | override fun checkServerTrusted(chain: Array, authType: String) {
23 | }
24 |
25 | override fun getAcceptedIssuers(): Array {
26 | return emptyArray()
27 | }
28 | }
29 |
30 | fun getSSLSocketFactory(certificates: List?): Pair {
31 | try {
32 | var manager: X509TrustManager? = null
33 | val trustManagers = prepareTrustManager(certificates)
34 | if (trustManagers != null) {
35 | manager = chooseTrustManager(trustManagers)
36 | }
37 | if (manager == null) {
38 | manager = UnSafeTrustManager
39 | }
40 | val sslContext = SSLContext.getInstance("TLS")
41 | sslContext.init(null, arrayOf(manager),SecureRandom())
42 | return Pair(sslContext.socketFactory, manager)
43 | } catch (e: NoSuchAlgorithmException) {
44 | throw e
45 | } catch (e: KeyManagementException) {
46 | throw e
47 | }
48 | }
49 |
50 | private fun prepareTrustManager(certificates: List?): Array? {
51 | if (certificates.isNullOrEmpty()) {
52 | return null
53 | }
54 | try {
55 | val certificateFactory = CertificateFactory.getInstance("X.509")
56 | val keyStore = KeyStore.getInstance(KeyStore.getDefaultType())
57 | keyStore.load(null, null)
58 | var index = 0
59 | for (certStream in certificates) {
60 | val certificateAlias = (index++).toString()
61 | val certificate = certificateFactory.generateCertificate(certStream)
62 | keyStore.setCertificateEntry(certificateAlias, certificate)
63 | try {
64 | certStream.close()
65 | } catch (e: IOException) {
66 | e.printStackTrace()
67 | }
68 | }
69 | val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
70 | tmf.init(keyStore)
71 | return tmf.trustManagers
72 | } catch (e: Exception) {
73 | e.printStackTrace()
74 | }
75 | return null
76 | }
77 |
78 | private fun chooseTrustManager(trustManagers: Array): X509TrustManager? {
79 | for (trustManager in trustManagers) {
80 | if (trustManager is X509TrustManager) {
81 | return trustManager
82 | }
83 | }
84 | return null
85 | }
86 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/image/transfrom/RoundCornerTransform.java:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.image.transfrom;
2 |
3 | import android.graphics.Bitmap;
4 | import android.graphics.BitmapShader;
5 | import android.graphics.Canvas;
6 | import android.graphics.Paint;
7 | import android.graphics.Path;
8 | import android.graphics.RectF;
9 | import android.graphics.Shader;
10 | import android.widget.ImageView;
11 |
12 | import androidx.annotation.NonNull;
13 |
14 | import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
15 | import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
16 | import com.bumptech.glide.load.resource.bitmap.TransformationUtils;
17 |
18 | import java.security.MessageDigest;
19 | import java.util.Arrays;
20 |
21 | /**
22 | * 圆角
23 | */
24 | public class RoundCornerTransform extends BitmapTransformation {
25 |
26 | private static final String ID = "com.jsy.tk.library.image.transfrom.RoundCornerTransform";
27 | private static final byte[] ID_BYTES = ID.getBytes(CHARSET);
28 |
29 | private float[] radii = null;
30 | private ImageView.ScaleType mScaleType;
31 |
32 | public RoundCornerTransform(ImageView.ScaleType scaleType, int leftTop, int rightTop, int rightBottom, int leftBottom) {
33 | this.mScaleType=scaleType;
34 | this.radii = new float[]{leftTop, leftTop, rightTop, rightTop, rightBottom, rightBottom, leftBottom, leftBottom};
35 | }
36 |
37 | @Override
38 | protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
39 | Bitmap source=null;
40 | if(mScaleType== ImageView.ScaleType.CENTER_CROP){
41 | source= TransformationUtils.centerCrop(pool,toTransform,outWidth,outHeight);
42 | }
43 | else if(mScaleType== ImageView.ScaleType.FIT_CENTER){
44 | source= TransformationUtils.fitCenter(pool,toTransform,outWidth,outHeight);
45 | }
46 | else {
47 | source=toTransform;
48 | }
49 | return roundCorner(pool, source);
50 | }
51 |
52 | private Bitmap roundCorner(BitmapPool pool, Bitmap source) {
53 | if (source == null) return null;
54 | int width = source.getWidth();
55 | int height = source.getHeight();
56 | Bitmap bitmap = pool.get(width, height, Bitmap.Config.ARGB_8888);
57 | if (bitmap == null) {
58 | bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
59 | }
60 | Canvas canvas = new Canvas(bitmap);
61 | Paint paint = new Paint();
62 | paint.setAntiAlias(true);
63 | paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
64 | RectF rect = new RectF(0, 0, width, height);
65 | Path path = new Path();
66 | path.addRoundRect(rect, radii, Path.Direction.CW);
67 | canvas.drawPath(path, paint);
68 |
69 | return bitmap;
70 | }
71 |
72 |
73 | @Override
74 | public boolean equals(Object o) {
75 | if (o instanceof RoundCornerTransform) {
76 | RoundCornerTransform other = (RoundCornerTransform) o;
77 | return Arrays.equals(radii,other.radii);
78 | }
79 | return false;
80 | }
81 |
82 | @Override
83 | public int hashCode() {
84 | return ID.hashCode();
85 | }
86 |
87 | @Override
88 | public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
89 | messageDigest.update(ID_BYTES);
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/utils/LogUtils.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.utils
2 |
3 | import android.content.Context
4 | import android.text.TextUtils
5 | import android.util.Log
6 |
7 | object LogUtils {
8 | var TAG_DEFAULT = "TKLOG"
9 | var debug = false
10 | private var context: Context? = null
11 |
12 | fun init(ctx: Context, isDebug: Boolean) {
13 | context = ctx.applicationContext
14 | debug = isDebug
15 | }
16 |
17 | fun v(msg: String?) {
18 | if (!debug) {
19 | return
20 | }
21 | v(TAG_DEFAULT, msg)
22 | }
23 |
24 | fun v(classs: Class<*>, msg: String) {
25 | if (!debug) {
26 | return
27 | }
28 | v(classs.simpleName, classs.simpleName + "==" + msg)
29 | }
30 |
31 | fun v(tag: String, msg: String?) {
32 | if (!debug) {
33 | return
34 | }
35 | log(Log.VERBOSE, tag, msg)
36 | }
37 |
38 | fun d(msg: String?) {
39 | if (!debug) {
40 | return
41 | }
42 | d(TAG_DEFAULT, msg)
43 | }
44 |
45 | fun d(classs: Class<*>, msg: String) {
46 | if (!debug) {
47 | return
48 | }
49 | d(classs.simpleName, classs.simpleName + "==" + msg)
50 | }
51 |
52 | fun d(tag: String, msg: String?) {
53 | if (!debug) {
54 | return
55 | }
56 | log(Log.DEBUG, tag, msg)
57 | }
58 |
59 | fun i(msg: String?) {
60 | if (!debug) {
61 | return
62 | }
63 | i(TAG_DEFAULT, msg)
64 | }
65 |
66 | fun i(classs: Class<*>, msg: String) {
67 | if (!debug) {
68 | return
69 | }
70 | i(classs.simpleName, classs.simpleName + "==" + msg)
71 | }
72 |
73 | fun i(tag: String, msg: String?) {
74 | if (!debug) {
75 | return
76 | }
77 | log(Log.INFO, tag, msg)
78 | }
79 |
80 | fun w(msg: String?) {
81 | if (!debug) {
82 | return
83 | }
84 | w(TAG_DEFAULT, msg)
85 | }
86 |
87 | fun w(classs: Class<*>, msg: String) {
88 | if (!debug) {
89 | return
90 | }
91 | w(classs.simpleName, classs.simpleName + "==" + msg)
92 | }
93 |
94 | fun w(tag: String, msg: String?) {
95 | if (!debug) {
96 | return
97 | }
98 | log(Log.WARN, tag, msg)
99 | }
100 |
101 | fun e(msg: String?) {
102 | if (!debug) {
103 | return
104 | }
105 | e(TAG_DEFAULT, msg)
106 | }
107 |
108 | fun e(classs: Class<*>, msg: String) {
109 | if (!debug) {
110 | return
111 | }
112 | e(classs.simpleName, classs.simpleName + "==" + msg)
113 | }
114 |
115 | fun e(tag: String, msg: String?) {
116 | if (!debug) {
117 | return
118 | }
119 | log(Log.ERROR, tag, msg)
120 | }
121 |
122 | //分段输出Log日志,单行最大输出约4000个字符
123 | private fun log(priority: Int, tag: String, msg: String?) {
124 | if (TextUtils.isEmpty(msg)) {
125 | return
126 | }
127 | var startIndex = 0
128 | var endIndex=0
129 | val totalLen = msg!!.length
130 | while (startIndex < totalLen) {
131 | endIndex=Math.min(startIndex+4000,totalLen)
132 | Log.println(priority,tag, msg.substring(startIndex, endIndex))
133 | startIndex=endIndex
134 | }
135 | }
136 |
137 | }
--------------------------------------------------------------------------------
/.idea/markdown-navigator.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | xmlns:android
17 |
18 | ^$
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 | xmlns:.*
28 |
29 | ^$
30 |
31 |
32 | BY_NAME
33 |
34 |
35 |
36 |
37 |
38 |
39 | .*:id
40 |
41 | http://schemas.android.com/apk/res/android
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | .*:name
51 |
52 | http://schemas.android.com/apk/res/android
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 | name
62 |
63 | ^$
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | style
73 |
74 | ^$
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 | .*
84 |
85 | ^$
86 |
87 |
88 | BY_NAME
89 |
90 |
91 |
92 |
93 |
94 |
95 | .*
96 |
97 | http://schemas.android.com/apk/res/android
98 |
99 |
100 | ANDROID_ATTRIBUTE_ORDER
101 |
102 |
103 |
104 |
105 |
106 |
107 | .*
108 |
109 | .*
110 |
111 |
112 | BY_NAME
113 |
114 |
115 |
116 |
117 |
118 |
119 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/mvvm/TKState.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.mvvm
2 |
3 | import com.jsy.tk.library.http.exception.ServerException
4 | import io.github.kongpf8848.rxhttp.sample.http.TKErrorCode
5 | import io.github.kongpf8848.rxhttp.sample.http.TKErrorCode.handleThrowable
6 | import io.github.kongpf8848.rxhttp.sample.http.TKResponse
7 | import io.github.kongpf8848.rxhttp.sample.http.exception.NullResponseException
8 |
9 | /**
10 | *将HttpCallback回调转化为对应的LiveData
11 | */
12 | class TKState {
13 |
14 | var state: Int = 0
15 | var code = TKErrorCode.ERRCODE_UNKNOWN
16 | var msg: String? = null
17 | var data: T? = null
18 | var progress: Long = 0
19 | var total: Long = 0
20 |
21 | @JvmOverloads
22 | constructor(state: Int, data: T? = null, msg: String? = "") {
23 | this.state = state
24 | this.data = data
25 | this.msg = msg
26 | }
27 |
28 | constructor(state: Int, throwable: Throwable?) {
29 | this.state = state
30 | handleThrowable(throwable).run {
31 | this@TKState.code = first
32 | this@TKState.msg = second
33 | }
34 | }
35 |
36 | constructor(state: Int, progress: Long, total: Long) {
37 | this.state = state
38 | this.progress = progress
39 | this.total = total
40 | }
41 |
42 | fun handle(handleCallback: HandleCallback.() -> Unit) {
43 | val callback = HandleCallback()
44 | callback.apply(handleCallback)
45 | when (state) {
46 | START -> {
47 | callback.onStart?.invoke()
48 | }
49 | SUCCESS -> {
50 | callback.onSuccess?.invoke(data)
51 | }
52 | FAIL -> {
53 | callback.onFailure?.invoke(code, msg)
54 | }
55 | PROGRESS -> {
56 | callback.onProgress?.invoke(progress, total)
57 | }
58 | }
59 | if (state == SUCCESS || state == FAIL) {
60 | callback.onComplete?.invoke()
61 | }
62 | }
63 |
64 | open class HandleCallback {
65 | var onStart: (() -> Unit)? = null
66 | var onSuccess: ((T?) -> Unit)? = null
67 | var onFailure: ((Int, String?) -> Unit)? = null
68 | var onComplete: (() -> Unit)? = null
69 | var onProgress: ((Long, Long) -> Unit)? = null
70 |
71 | fun onStart(callback: (() -> Unit)?) {
72 | this.onStart = callback
73 | }
74 |
75 | fun onSuccess(callback: ((T?) -> Unit)?) {
76 | this.onSuccess = callback
77 | }
78 |
79 | fun onFailure(callback: ((Int, String?) -> Unit)?) {
80 | this.onFailure = callback
81 | }
82 |
83 | fun onComplete(callback: (() -> Unit)?) {
84 | this.onComplete = callback
85 | }
86 |
87 | fun onProgress(callback: ((Long, Long) -> Unit)?) {
88 | this.onProgress = callback
89 | }
90 | }
91 |
92 | companion object {
93 | const val START = 0
94 | const val SUCCESS = 1
95 | const val FAIL = 2
96 | const val PROGRESS = 3
97 |
98 | fun start(): TKState {
99 | return TKState(START)
100 | }
101 |
102 | fun response(response: TKResponse?): TKState {
103 | if (response != null) {
104 | if (response.isSuccess()) {
105 | return TKState(SUCCESS, response.data, null)
106 | } else {
107 | return error(ServerException(response.code, response.msg))
108 | }
109 |
110 | } else {
111 | return error(NullResponseException(TKErrorCode.ERRCODE_RESPONSE_NULL, TKErrorCode.ERRCODE_RESPONSE_NULL_DESC))
112 | }
113 |
114 | }
115 |
116 | fun error(t: Throwable?): TKState {
117 | return TKState(FAIL, t)
118 | }
119 |
120 | fun progress(progress: Long, total: Long): TKState {
121 | return TKState(PROGRESS, progress, total)
122 | }
123 | }
124 |
125 | }
126 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/mvc/MVCApi.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.mvc
2 |
3 | import android.content.Context
4 | import com.jsy.tk.library.http.exception.ServerException
5 | import io.github.kongpf8848.rxhttp.RxHttp
6 | import io.github.kongpf8848.rxhttp.callback.HttpCallback
7 | import io.github.kongpf8848.rxhttp.sample.http.TKErrorCode
8 | import io.github.kongpf8848.rxhttp.sample.http.TKErrorCode.handleThrowable
9 | import io.github.kongpf8848.rxhttp.sample.http.TKResponse
10 | import io.github.kongpf8848.rxhttp.sample.http.exception.NullResponseException
11 |
12 | object MVCApi {
13 |
14 | /**
15 | * GET请求
16 | * context:上下文
17 | * url:请求url
18 | * params:参数列表,可为null
19 | * tag:标识一个网络请求
20 | * callback:网络请求回调
21 | */
22 | inline fun httpGet(
23 | context: Context,
24 | url: String,
25 | params: Map?,
26 | tag: Any? = null,
27 | callback: MVCHttpCallback
28 | ) {
29 | RxHttp.getInstance().get(context)
30 | .url(url)
31 | .params(params)
32 | .tag(tag)
33 | .enqueue(simpleHttpCallback(callback))
34 | }
35 |
36 | /**
37 | * POST请求
38 | * context:上下文
39 | * url:请求url
40 | * params:参数列表,可为null
41 | * tag:标识一个网络请求
42 | * callback:网络请求回调
43 | */
44 | inline fun httpPost(
45 | context: Context,
46 | url: String,
47 | params: Map?,
48 | tag: Any? = null,
49 | callback: MVCHttpCallback
50 | ) {
51 | RxHttp.getInstance().post(context)
52 | .url(url)
53 | .params(params)
54 | .tag(tag)
55 | .enqueue(simpleHttpCallback(callback))
56 | }
57 |
58 | inline fun httpPostForm(
59 | context: Context,
60 | url: String,
61 | params: Map?,
62 | tag: Any? = null,
63 | callback: MVCHttpCallback
64 | ) {
65 |
66 | RxHttp.getInstance().postForm(context)
67 | .url(url)
68 | .params(params)
69 | .tag(tag)
70 | .enqueue(simpleHttpCallback(callback))
71 | }
72 |
73 | inline fun httpPut(
74 | context: Context,
75 | url: String,
76 | params: Map?,
77 | tag: Any? = null,
78 | callback: MVCHttpCallback
79 | ) {
80 |
81 | RxHttp.getInstance().put(context)
82 | .url(url)
83 | .params(params)
84 | .tag(tag)
85 | .enqueue(simpleHttpCallback(callback))
86 | }
87 |
88 | inline fun httpDelete(
89 | context: Context,
90 | url: String,
91 | params: Map?,
92 | tag: Any? = null,
93 | callback: MVCHttpCallback
94 | ) {
95 | RxHttp.getInstance().delete(context)
96 | .url(url)
97 | .params(params)
98 | .tag(tag)
99 | .enqueue(simpleHttpCallback(callback))
100 | }
101 |
102 | /**
103 | *上传
104 | *支持上传多个文件,map中对应的value类型为File类型或Uri类型
105 | *支持监听上传进度
106 | val map =Map()
107 | map.put("model", "xiaomi")
108 | map.put("os", "android")
109 | map.put("avatar",File("xxx"))
110 | map.put("video",uri)
111 | */
112 | inline fun httpUpload(
113 | context: Context,
114 | url: String,
115 | params: Map?,
116 | tag: Any? = null,
117 | callback: MVCHttpCallback
118 | ) {
119 | RxHttp.getInstance().upload(context)
120 | .url(url)
121 | .params(params)
122 | .tag(tag)
123 | .enqueue(simpleHttpCallback(callback))
124 |
125 | }
126 |
127 |
128 | inline fun simpleHttpCallback(callback: MVCHttpCallback): HttpCallback> {
129 | return object : HttpCallback>(callback.getType()) {
130 | override fun onStart() {
131 | super.onStart()
132 | callback.onStart()
133 | }
134 |
135 | override fun onNext(response: TKResponse?) {
136 | if (response != null) {
137 | if (response.isSuccess()) {
138 | callback.onSuccess(response.data)
139 | } else {
140 | return onError(ServerException(response.code, response.msg))
141 | }
142 |
143 | } else {
144 | return onError(NullResponseException(TKErrorCode.ERRCODE_RESPONSE_NULL, TKErrorCode.ERRCODE_RESPONSE_NULL_DESC))
145 | }
146 |
147 | }
148 |
149 | override fun onError(e: Throwable?) {
150 | handleThrowable(e).run {
151 | callback.onFailure(first, second)
152 | }
153 | }
154 |
155 | override fun onComplete() {
156 | super.onComplete()
157 | callback.onComplete()
158 | }
159 |
160 | override fun onProgress(readBytes: Long, totalBytes: Long) {
161 | super.onProgress(readBytes, totalBytes)
162 | callback.onProgress(readBytes, totalBytes)
163 | }
164 | }
165 | }
166 |
167 |
168 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/mvvm/NetworkRepository.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.mvvm
2 |
3 | import android.content.Context
4 | import androidx.lifecycle.MutableLiveData
5 | import io.github.kongpf8848.rxhttp.RxHttp
6 | import io.github.kongpf8848.rxhttp.callback.DownloadCallback
7 | import io.github.kongpf8848.rxhttp.callback.HttpCallback
8 | import io.github.kongpf8848.rxhttp.sample.http.TKResponse
9 |
10 | /**
11 | * MVVM架构网络仓库
12 | * UI->ViewModel->Repository->LiveData(ViewModel)->UI
13 | */
14 | class NetworkRepository private constructor() {
15 |
16 | companion object {
17 | val instance = NetworkRepository.holder
18 | }
19 |
20 | private object NetworkRepository {
21 | val holder = NetworkRepository()
22 | }
23 |
24 | inline fun wrapHttpCallback(): MvvmHttpCallback {
25 | return object : MvvmHttpCallback() {
26 |
27 | }
28 | }
29 |
30 | inline fun newCallback(liveData: MutableLiveData>): HttpCallback> {
31 | val type = wrapHttpCallback().getType()
32 | return object : HttpCallback>(type) {
33 | override fun onStart() {
34 | liveData.value = TKState.start()
35 | }
36 |
37 | override fun onNext(response: TKResponse?) {
38 | liveData.value = TKState.response(response)
39 | }
40 |
41 | override fun onError(e: Throwable?) {
42 | liveData.value = TKState.error(e)
43 | }
44 |
45 | override fun onComplete() {
46 |
47 | /**
48 | * 亲,此处不要做任何操作,不要给LiveData赋值,防止onNext对应的LiveData数据被覆盖,
49 | * 在TKState类handle方法里会特别处理回调的,放心好了
50 | */
51 | }
52 |
53 | override fun onProgress(readBytes: Long, totalBytes: Long) {
54 | liveData.value = TKState.progress(readBytes, totalBytes)
55 | }
56 | }
57 | }
58 |
59 | inline fun httpGet(
60 | context: Context,
61 | url: String,
62 | params: Map?,
63 | tag: Any? = null
64 | ): MutableLiveData> {
65 | val liveData = MutableLiveData>()
66 | RxHttp.getInstance()
67 | .get(context)
68 | .url(url)
69 | .params(params)
70 | .tag(tag)
71 | .enqueue(newCallback(liveData))
72 | return liveData
73 | }
74 |
75 |
76 | inline fun httpPost(
77 | context: Context,
78 | url: String,
79 | params: Map?,
80 | tag: Any? = null
81 | ): MutableLiveData> {
82 | val liveData = MutableLiveData>()
83 | RxHttp.getInstance().post(context)
84 | .url(url)
85 | .params(params)
86 | .tag(tag)
87 | .enqueue(newCallback(liveData))
88 | return liveData
89 | }
90 |
91 | inline fun httpPostForm(
92 | context: Context,
93 | url: String,
94 | params: Map?,
95 | tag: Any? = null
96 | ): MutableLiveData> {
97 | val liveData = MutableLiveData>()
98 | RxHttp.getInstance().postForm(context)
99 | .url(url)
100 | .params(params)
101 | .tag(tag)
102 | .enqueue(newCallback(liveData))
103 | return liveData
104 | }
105 |
106 | inline fun httpPut(
107 | context: Context,
108 | url: String,
109 | params: Map?,
110 | tag: Any? = null
111 | ): MutableLiveData> {
112 | val liveData = MutableLiveData>()
113 | RxHttp.getInstance().put(context)
114 | .url(url)
115 | .params(params)
116 | .tag(tag)
117 | .enqueue(newCallback(liveData))
118 | return liveData
119 | }
120 |
121 | inline fun httpDelete(
122 | context: Context,
123 | url: String,
124 | params: Map?,
125 | tag: Any? = null
126 | ): MutableLiveData> {
127 | val liveData = MutableLiveData>()
128 | RxHttp.getInstance().delete(context)
129 | .params(params)
130 | .url(url)
131 | .tag(tag)
132 | .enqueue(newCallback(liveData))
133 | return liveData
134 | }
135 |
136 |
137 | /**
138 | *上传
139 | *支持上传多个文件,map中对应的value类型为File类型或Uri类型
140 | *支持监听上传进度
141 | val map =Map()
142 | map.put("model", "xiaomi")
143 | map.put("os", "android")
144 | map.put("avatar",File("xxx"))
145 | map.put("video",uri)
146 | */
147 | inline fun httpUpload(
148 | context: Context,
149 | url: String,
150 | params: Map?,
151 | tag: Any? = null
152 | ): MutableLiveData> {
153 | val liveData = MutableLiveData>()
154 | RxHttp.getInstance().upload(context)
155 | .url(url)
156 | .params(params)
157 | .tag(tag)
158 | .enqueue(newCallback(liveData))
159 | return liveData
160 | }
161 |
162 |
163 | /**
164 | * 下载
165 | * context:上下文,如不需要和生命周期绑定,应该传递applicationContext
166 | * url:下载地址
167 | * dir:本地目录路径
168 | * filename:保存文件名称
169 | * callback:下载进度回调
170 | * md5:下载文件的MD5值
171 | * breakpoint:是否支持断点下载,默认为true
172 | */
173 | fun httpDownload(context: Context, url: String, dir: String, filename: String, callback: DownloadCallback, md5: String? = null, breakPoint: Boolean = true, tag: Any? = null) {
174 | RxHttp.getInstance().download(context).dir(dir).filename(filename).breakpoint(breakPoint).md5(md5).url(url).tag(tag).enqueue(callback)
175 | }
176 |
177 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
11 |
16 |
21 |
26 |
31 |
36 |
41 |
46 |
51 |
56 |
61 |
66 |
71 |
76 |
81 |
86 |
91 |
96 |
101 |
106 |
111 |
116 |
121 |
126 |
131 |
136 |
141 |
146 |
151 |
156 |
161 |
166 |
171 |
172 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/activity/MVVMActivity.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.activity
2 |
3 | import android.app.ProgressDialog
4 | import android.content.Intent
5 | import android.os.Build
6 | import android.os.Bundle
7 | import io.github.kongpf8848.commonhelper.ToastHelper
8 | import io.github.kongpf8848.rxhttp.sample.R
9 | import io.github.kongpf8848.rxhttp.sample.databinding.ActivityMainBinding
10 | import io.github.kongpf8848.rxhttp.sample.databinding.ActivityMvvmBinding
11 | import io.github.kongpf8848.rxhttp.sample.extension.getContent
12 | import io.github.kongpf8848.rxhttp.sample.extension.observeState
13 | import io.github.kongpf8848.rxhttp.sample.http.TKURL
14 | import io.github.kongpf8848.rxhttp.sample.mvvm.BaseMvvmActivity
15 | import io.github.kongpf8848.rxhttp.sample.service.DownloadService
16 | import io.github.kongpf8848.rxhttp.sample.utils.LogUtils
17 | import io.github.kongpf8848.rxhttp.sample.viewmodel.MainViewModel
18 |
19 |
20 | /**
21 | * MVVM架构使用RxHttp示例
22 | */
23 | class MVVMActivity : BaseMvvmActivity() {
24 |
25 | private var progressDialog: ProgressDialog? = null
26 |
27 |
28 | private val params: Map = hashMapOf("name" to "jack", "location" to "shanghai", "age" to 28)
29 |
30 |
31 | override fun onCreateEnd(savedInstanceState: Bundle?) {
32 | super.onCreateEnd(savedInstanceState)
33 |
34 | binding.button1.setOnClickListener {
35 | onButtonGet()
36 | }
37 | binding.button2.setOnClickListener {
38 | onButtonPost()
39 | }
40 | binding.button3.setOnClickListener {
41 | onButtonPostForm()
42 | }
43 | binding.button4.setOnClickListener {
44 | onButtonPut()
45 | }
46 | binding.button5.setOnClickListener {
47 | onButtonDelete()
48 | }
49 | binding.button6.setOnClickListener {
50 | onButtonUpload()
51 | }
52 | binding.button7.setOnClickListener {
53 | onButtonDownload()
54 | }
55 | }
56 |
57 | /**
58 | * GET请求
59 | */
60 | private fun onButtonGet() {
61 | viewModel.testGet(null).observeState(this) {
62 | onStart {
63 | LogUtils.d(TAG, "onButtonGet() onStart called")
64 | }
65 | onSuccess {
66 | LogUtils.d(TAG, "onButtonGet() onSuccess called:${it}")
67 | }
68 | onFailure { code, msg ->
69 | ToastHelper.toast("onButtonGet() onFailure,code:${code},msg:${msg}")
70 | }
71 | onComplete {
72 | LogUtils.d(TAG, "onButtonGet() onComplete called")
73 | }
74 | }
75 |
76 | }
77 |
78 | /**
79 | * POST请求
80 | */
81 | private fun onButtonPost() {
82 |
83 | viewModel.testPost(params).observeState(this) {
84 | onStart {
85 | LogUtils.d(TAG, "onButtonPost() onStart called")
86 | }
87 | onSuccess {
88 | LogUtils.d(TAG, "onButtonPost() onSuccess called:${it}")
89 | }
90 | onFailure { code, msg ->
91 | ToastHelper.toast("onButtonPost() onFailure,code:${code},msg:${msg}")
92 | }
93 | onComplete {
94 | LogUtils.d(TAG, "onButtonPost() onComplete called")
95 | }
96 | }
97 | }
98 |
99 | /**
100 | * POST FORM请求
101 | */
102 | private fun onButtonPostForm() {
103 |
104 | viewModel.testPostForm(params).observeState(this) {
105 | onStart {
106 | LogUtils.d(TAG, "onButtonPostForm() onStart called")
107 | }
108 | onSuccess {
109 | LogUtils.d(TAG, "onButtonPostForm() onSuccess called:${it}")
110 | }
111 | onFailure { code, msg ->
112 | ToastHelper.toast("onButtonPostForm onFailure,code:${code},msg:${msg}")
113 | }
114 | onComplete {
115 | LogUtils.d(TAG, "onButtonPostForm() onComplete called")
116 | }
117 | }
118 | }
119 |
120 | /**
121 | * PUT请求
122 | */
123 | private fun onButtonPut() {
124 |
125 | viewModel.testPut(params).observeState(this) {
126 | onStart {
127 | LogUtils.d(TAG, "onButtonPut() onStart called")
128 | }
129 | onSuccess {
130 | LogUtils.d(TAG, "onButtonPut() onSuccess called:${it}")
131 | }
132 | onFailure { code, msg ->
133 | ToastHelper.toast("onButtonPut() onFailure,code:${code},msg:${msg}")
134 | }
135 | onComplete {
136 | LogUtils.d(TAG, "onButtonPut() onComplete called")
137 | }
138 | }
139 | }
140 |
141 | /**
142 | * DELETE请求
143 | */
144 | private fun onButtonDelete() {
145 |
146 | viewModel.testDelete(params).observeState(this) {
147 | onStart {
148 | LogUtils.d(TAG, "onButtonDelete() onStart called")
149 | }
150 | onSuccess {
151 | LogUtils.d(TAG, "onButtonDelete() onSuccess called:${it}")
152 | }
153 | onFailure { code, msg ->
154 | ToastHelper.toast("onButtonDelete() onFailure,code:${code},msg:${msg}")
155 | }
156 | onComplete {
157 | LogUtils.d(TAG, "onButtonDelete() onComplete called")
158 | }
159 | }
160 | }
161 |
162 | /**
163 | * 上传,实在找不到如何很好的方法去模拟演示上传的过程,亲,要不咱搭建一个Tomcat服务器,然后再写一个上传接口,自己动手,丰衣足食
164 | */
165 | private fun onButtonUpload() {
166 | getContent("image/*") {
167 | val map: MutableMap = HashMap()
168 | map["model"] = Build.MODEL
169 | map["manufacturer"] = Build.MANUFACTURER
170 | map["os"] = Build.VERSION.SDK_INT
171 | map["image"] = it
172 |
173 | viewModel.testUpload(map).observeState(this){
174 | onStart{
175 | LogUtils.d(TAG, "onButtonUpload() onStart called")
176 | showProgressDialog("正在上传,请稍等...")
177 | }
178 |
179 | onProgress { progress, total ->
180 | LogUtils.d(TAG, "onButtonUpload() onProgress called with: progress = $progress, total = $total")
181 | updateProgress(progress, total)
182 | }
183 |
184 | onSuccess {
185 | LogUtils.d(TAG, "onButtonUpload() onSuccess called:${it}")
186 | ToastHelper.toast("上传成功,返回结果:${it}")
187 | }
188 |
189 | onFailure { code, msg ->
190 | LogUtils.d(TAG, "onButtonUpload() onFailure called with: code = $code, msg = $msg")
191 | ToastHelper.toast("上传失败,code:${code},msg:${msg}")
192 | }
193 |
194 | onComplete{
195 | LogUtils.d(TAG, "onButtonUpload() onComplete called")
196 | closeProgressDialog()
197 | }
198 | }
199 | }
200 | }
201 |
202 |
203 | /**
204 | * 下载
205 | */
206 | fun onButtonDownload() {
207 | /**
208 | * 启动Service进行下载
209 | */
210 | val intent= Intent(this, DownloadService::class.java)
211 | intent.putExtra("url",TKURL.URL_DOWNLOAD)
212 | startService(intent)
213 | }
214 |
215 | private fun showProgressDialog(title: String) {
216 | progressDialog = ProgressDialog(this)
217 | progressDialog?.apply {
218 | setMessage(title)
219 | setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
220 | setCanceledOnTouchOutside(false)
221 | setCancelable(false)
222 | show()
223 | }
224 | }
225 |
226 | private fun updateProgress(progress: Long, total: Long) {
227 | LogUtils.d(TAG, "updateProgress,readBytes:$progress,totalBytes:$total")
228 | progressDialog?.apply {
229 | if(isShowing){
230 | this.progress = progress.toInt()
231 | this.max=total.toInt()
232 | setProgressNumberFormat(String.format("%.2fM/%.2fM", progress * 1.0f / 1024 / 1024, total * 1.0f / 1024 / 1024))
233 | }
234 | }
235 | }
236 |
237 | private fun closeProgressDialog() {
238 | progressDialog?.dismiss()
239 | }
240 | }
241 |
242 |
243 |
244 |
245 |
246 |
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/service/DownloadService.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.service
2 |
3 | import android.app.NotificationManager
4 | import android.app.PendingIntent
5 | import android.app.Service
6 | import android.content.Context
7 | import android.content.Intent
8 | import android.os.*
9 | import android.text.TextUtils
10 | import android.util.Log
11 | import androidx.core.app.NotificationCompat
12 | import io.github.kongpf8848.commonhelper.NotificationHelper
13 | import io.github.kongpf8848.commonhelper.StorageHelper
14 | import io.github.kongpf8848.commonhelper.ToastHelper
15 | import io.github.kongpf8848.commonhelper.bean.NotificationInfo
16 | import io.github.kongpf8848.rxhttp.bean.DownloadInfo
17 | import io.github.kongpf8848.rxhttp.callback.DownloadCallback
18 | import io.github.kongpf8848.rxhttp.sample.R
19 | import io.github.kongpf8848.rxhttp.sample.mvvm.NetworkRepository
20 | import io.github.kongpf8848.rxhttp.sample.utils.ApkUtils
21 | import io.github.kongpf8848.rxhttp.sample.utils.LogUtils
22 | import java.io.File
23 | import java.text.DecimalFormat
24 | import java.util.*
25 |
26 | /**
27 | * 下载APK
28 | */
29 | class DownloadService : Service() {
30 |
31 | lateinit var dir: String
32 | lateinit var filename: String
33 |
34 | lateinit var notificationBuilder: NotificationCompat.Builder
35 | lateinit var notificationManager: NotificationManager
36 | private var handlerThread: HandlerThread? = null
37 | private var handler: DownloadHandler? = null
38 |
39 | private var urlList = mutableListOf()
40 |
41 | companion object {
42 | const val TAG = "DownloadService"
43 | const val DOWNLOAD_NOTIFY_ID = 1005
44 | const val MSG_SHOW_NOTIFICATION = 0
45 | const val MSG_UPDATE_NOTIFICATION = 1
46 | const val MSG_CANCEL_NOTIFICATION = 2
47 | const val MSG_INSTALL_APK = 3
48 | }
49 |
50 |
51 | /**
52 | * 处理更新通知栏的操作放在子线程操作,避免影响主线程
53 | */
54 | inner class DownloadHandler(looper: Looper) : Handler(looper) {
55 |
56 | override fun handleMessage(msg: Message) {
57 | when (msg.what) {
58 | MSG_SHOW_NOTIFICATION -> {
59 | notificationManager.notify(DOWNLOAD_NOTIFY_ID, notificationBuilder.build())
60 | }
61 |
62 | MSG_UPDATE_NOTIFICATION -> {
63 | val pair = msg.obj as Pair
64 | val progress = pair.first
65 | val total = pair.second
66 | val percentFloat = DecimalFormat("0.00").format(progress * 1.0f / total)
67 | val percentInt = (percentFloat.toDouble() * 100).toInt()
68 | Log.d(
69 | TAG,
70 | "handleMessage() called with: progress = ${progress}, total = ${total},percentFloat:${percentFloat},percentInt:${percentInt}"
71 | )
72 | var content = ""
73 | content = if (percentInt < 100) {
74 | applicationContext.resources.getString(
75 | R.string.download_progress,
76 | percentInt
77 | )
78 | } else {
79 | applicationContext.resources.getString(R.string.download_success)
80 | }
81 | notificationBuilder.setContentText(content).setProgress(100, percentInt, false)
82 | notificationManager.notify(DOWNLOAD_NOTIFY_ID, notificationBuilder.build())
83 | }
84 |
85 | MSG_CANCEL_NOTIFICATION -> {
86 | notificationManager.cancel(DOWNLOAD_NOTIFY_ID)
87 | }
88 |
89 | MSG_INSTALL_APK -> {
90 | ApkUtils.installApk(
91 | applicationContext,
92 | File(dir, filename),
93 | "$packageName.fileprovider"
94 | )
95 | }
96 | }
97 | }
98 | }
99 |
100 |
101 | private var downloadCallback = object : DownloadCallback() {
102 |
103 | var url: String = ""
104 |
105 | override fun onStart() {
106 | ToastHelper.toast("开始下载,可在通知栏查看进度")
107 | handler?.sendEmptyMessage(MSG_SHOW_NOTIFICATION)
108 | }
109 |
110 |
111 | override fun onProgress(readBytes: Long, totalBytes: Long) {
112 | LogUtils.d(
113 | TAG,
114 | "onProgress() called with: readBytes = $readBytes, totalBytes = $totalBytes"
115 | )
116 | handler?.sendMessage(
117 | Message.obtain(
118 | handler,
119 | MSG_UPDATE_NOTIFICATION,
120 | Pair(readBytes, totalBytes)
121 | )
122 | )
123 |
124 | }
125 |
126 | override fun onNext(response: DownloadInfo?) {
127 | LogUtils.d(TAG, "onNext() called with: response = $response")
128 | handler?.sendEmptyMessage(MSG_INSTALL_APK)
129 | }
130 |
131 | override fun onError(e: Throwable?) {
132 | LogUtils.d(TAG, "onError() called with: e = $e")
133 | handler?.sendEmptyMessage(MSG_CANCEL_NOTIFICATION)
134 | urlList.remove(url)
135 | LogUtils.d(TAG, "onError() called,urlList-size:${urlList.size}")
136 | }
137 |
138 | override fun onComplete() {
139 | LogUtils.d(TAG, "onComplete() called")
140 | handler?.sendEmptyMessage(MSG_CANCEL_NOTIFICATION)
141 | urlList.remove(url)
142 | LogUtils.d(TAG, "onComplete() called,urlList-size:${urlList.size}")
143 | }
144 |
145 | }
146 |
147 |
148 | override fun onBind(intent: Intent?): IBinder? {
149 | return null
150 | }
151 |
152 |
153 | override fun onCreate() {
154 | super.onCreate()
155 |
156 | dir = StorageHelper.getExternalSandBoxPath(
157 | applicationContext,
158 | Environment.DIRECTORY_DOWNLOADS
159 | )
160 |
161 | notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
162 | notificationBuilder = NotificationHelper.getNotificationBuilder(
163 | applicationContext,
164 | NotificationInfo("001", "Category", "001", "Download")
165 | )
166 | .setOnlyAlertOnce(true)
167 | .setSmallIcon(R.mipmap.ic_launcher)
168 | .setContentIntent(
169 | PendingIntent.getActivity(
170 | applicationContext,
171 | 0,
172 | Intent(),
173 | PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
174 | )
175 | )
176 | .setContentTitle("正在下载新版本,请稍等...")
177 | .setAutoCancel(true)
178 | .setOngoing(true)
179 | .setProgress(100, 0, false);
180 |
181 |
182 | val handlerThread = HandlerThread("DownloadHandlerThread")
183 | handlerThread.start()
184 | handler = DownloadHandler(handlerThread.looper)
185 |
186 | }
187 |
188 | override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
189 | val urlLink = intent?.getStringExtra("url")
190 | val md5 = intent?.getStringExtra("md5")
191 | if (!TextUtils.isEmpty(urlLink)) {
192 | if (urlList.contains(urlLink)) {
193 | ToastHelper.toast("url:${urlLink} is exists in downloading!!!")
194 | return super.onStartCommand(intent, flags, startId)
195 | }
196 | urlList.add(urlLink!!)
197 | LogUtils.d(TAG, "onStartCommand called,urlList-size:${urlList.size}")
198 | filename = urlLink.substring(urlLink.lastIndexOf(File.separator) + 1)
199 | if (TextUtils.isEmpty(filename)) {
200 | filename = UUID.randomUUID().toString()
201 | }
202 | NetworkRepository.instance.httpDownload(
203 | context = applicationContext,
204 | url = urlLink,
205 | dir = dir,
206 | filename = filename,
207 | callback = downloadCallback.apply {
208 | url = urlLink
209 | },
210 | md5 = md5
211 | )
212 | }
213 | return super.onStartCommand(intent, flags, startId)
214 | }
215 |
216 |
217 | override fun onDestroy() {
218 | super.onDestroy()
219 | handler?.removeCallbacksAndMessages(null)
220 | handlerThread?.quit()
221 | }
222 |
223 |
224 | }
--------------------------------------------------------------------------------
/app/src/main/java/io/github/kongpf8848/rxhttp/sample/activity/MVCActivity.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp.sample.activity
2 |
3 | import android.content.Intent
4 | import android.os.Build
5 | import android.os.Bundle
6 | import android.util.Log
7 | import androidx.databinding.DataBindingUtil
8 | import io.github.kongpf8848.rxhttp.sample.R
9 | import io.github.kongpf8848.rxhttp.sample.base.BaseActivity
10 | import io.github.kongpf8848.rxhttp.sample.bean.Banner
11 | import io.github.kongpf8848.rxhttp.sample.bean.User
12 | import io.github.kongpf8848.rxhttp.sample.databinding.ActivityMvcBinding
13 | import io.github.kongpf8848.rxhttp.sample.extension.getContent
14 | import io.github.kongpf8848.rxhttp.sample.http.TKURL
15 | import io.github.kongpf8848.rxhttp.sample.mvc.MVCApi
16 | import io.github.kongpf8848.rxhttp.sample.mvc.MVCHttpCallback
17 | import io.github.kongpf8848.rxhttp.sample.service.DownloadService
18 | import io.github.kongpf8848.rxhttp.sample.utils.LogUtils
19 | /**
20 | * MVC架构使用RxHttp示例
21 | */
22 | class MVCActivity : BaseActivity() {
23 |
24 | private val params: Map? = hashMapOf("name" to "jack", "location" to "shanghai", "age" to 28)
25 |
26 | override fun onCreate(savedInstanceState: Bundle?) {
27 | super.onCreate(savedInstanceState)
28 | val binding = DataBindingUtil.setContentView(this, R.layout.activity_mvc)
29 | binding.lifecycleOwner = this
30 | binding.button1.setOnClickListener {
31 | onButtonGet()
32 | }
33 | binding.button2.setOnClickListener {
34 | onButtonPost()
35 | }
36 | binding.button3.setOnClickListener {
37 | onButtonPostForm()
38 | }
39 | binding.button4.setOnClickListener {
40 | onButtonPut()
41 | }
42 | binding.button5.setOnClickListener {
43 | onButtonDelete()
44 | }
45 | binding.button6.setOnClickListener {
46 | onButtonUpload()
47 | }
48 | binding.button7.setOnClickListener {
49 | onButtonDownload()
50 | }
51 | }
52 |
53 | private fun onButtonGet() {
54 |
55 | MVCApi.httpGet(context = baseActivity,
56 | url = TKURL.URL_GET,
57 | params = null,
58 | tag = null, callback = object : MVCHttpCallback>() {
59 | override fun onStart() {
60 | LogUtils.d(TAG, "onButtonGet onStart() called")
61 | }
62 |
63 | override fun onSuccess(result: List?) {
64 | Log.d(TAG, "onButtonGet onSuccess() called with: result = $result")
65 | }
66 |
67 | override fun onFailure(code: Int, msg: String?) {
68 | Log.d(TAG, "onButtonGet onFailure() called with: code = $code, msg = $msg")
69 | }
70 |
71 | override fun onComplete() {
72 | Log.d(TAG, "onButtonGet onComplete() called")
73 | }
74 |
75 |
76 | })
77 | }
78 |
79 | private fun onButtonPost() {
80 | MVCApi.httpPost(context = baseActivity,
81 | url = TKURL.URL_POST,
82 | params = params,
83 | tag = null,
84 | callback = object : MVCHttpCallback() {
85 | override fun onStart() {
86 | super.onStart()
87 | Log.d(TAG, "onButtonPost onStart() called")
88 | }
89 |
90 | override fun onSuccess(result: User?) {
91 | Log.d(TAG, "onButtonPost onSuccess() called with: result = $result")
92 | }
93 |
94 | override fun onFailure(code: Int, msg: String?) {
95 | Log.d(TAG, "onButtonPost onFailure() called with: code = $code, msg = $msg")
96 | }
97 |
98 | override fun onComplete() {
99 | super.onComplete()
100 | Log.d(TAG, "onButtonPost onComplete() called")
101 | }
102 | })
103 | }
104 |
105 | private fun onButtonPostForm() {
106 | MVCApi.httpPostForm(context = baseActivity,
107 | url = TKURL.URL_POST_FORM,
108 | params = params,
109 | tag = null,
110 | callback = object : MVCHttpCallback() {
111 | override fun onStart() {
112 | super.onStart()
113 | Log.d(TAG, "onButtonPostForm onStart() called")
114 | }
115 |
116 | override fun onSuccess(result: User?) {
117 | Log.d(TAG, "onButtonPostForm onSuccess() called with: result = $result")
118 | }
119 |
120 | override fun onFailure(code: Int, msg: String?) {
121 | Log.d(TAG, "onButtonPostForm onFailure() called with: code = $code, msg = $msg")
122 | }
123 |
124 | override fun onComplete() {
125 | super.onComplete()
126 | Log.d(TAG, "onButtonPostForm onComplete() called")
127 | }
128 | })
129 | }
130 |
131 | private fun onButtonPut() {
132 | MVCApi.httpPut(context = baseActivity,
133 | url = TKURL.URL_PUT,
134 | params = params,
135 | tag = null,
136 | callback = object : MVCHttpCallback() {
137 | override fun onStart() {
138 | super.onStart()
139 | Log.d(TAG, "onButtonPut onStart() called")
140 | }
141 |
142 | override fun onSuccess(result: User?) {
143 | Log.d(TAG, "onButtonPut onSuccess() called with: result = $result")
144 | }
145 |
146 | override fun onFailure(code: Int, msg: String?) {
147 | Log.d(TAG, "onButtonPut onFailure() called with: code = $code, msg = $msg")
148 | }
149 |
150 | override fun onComplete() {
151 | super.onComplete()
152 | Log.d(TAG, "onButtonPut onComplete() called")
153 | }
154 | })
155 | }
156 |
157 | private fun onButtonDelete() {
158 | MVCApi.httpDelete(context = baseActivity,
159 | url = TKURL.URL_DELETE,
160 | params = params,
161 | tag = null,
162 | callback = object : MVCHttpCallback() {
163 | override fun onStart() {
164 | super.onStart()
165 | Log.d(TAG, "onButtonDelete onStart() called")
166 | }
167 |
168 | override fun onSuccess(result: User?) {
169 | Log.d(TAG, "onButtonDelete onSuccess() called with: result = $result")
170 | }
171 |
172 | override fun onFailure(code: Int, msg: String?) {
173 | Log.d(TAG, "onButtonDelete onFailure() called with: code = $code, msg = $msg")
174 | }
175 |
176 | override fun onComplete() {
177 | super.onComplete()
178 | Log.d(TAG, "onButtonDelete onComplete() called")
179 | }
180 | })
181 | }
182 |
183 | private fun onButtonUpload() {
184 | getContent("image/*") {
185 | val map: MutableMap = HashMap()
186 | map["model"] = Build.MODEL
187 | map["manufacturer"] = Build.MANUFACTURER
188 | map["os"] = Build.VERSION.SDK_INT
189 | map["image"] = it
190 |
191 | MVCApi.httpUpload(context = baseActivity,
192 | url = TKURL.URL_UPLOAD,
193 | params = map,
194 | tag = null,
195 | callback = object : MVCHttpCallback() {
196 | override fun onStart() {
197 | super.onStart()
198 | Log.d(TAG, "onButtonUpload onStart() called")
199 | }
200 |
201 | override fun onProgress(readBytes: Long, totalBytes: Long) {
202 | super.onProgress(readBytes, totalBytes)
203 | Log.d(TAG, "onButtonUpload onProgress() called with: readBytes = $readBytes, totalBytes = $totalBytes")
204 | }
205 |
206 | override fun onSuccess(result: String?) {
207 | Log.d(TAG, "onButtonUpload onSuccess() called with: result = $result")
208 | }
209 |
210 | override fun onFailure(code: Int, msg: String?) {
211 | Log.d(TAG, "onButtonUpload onFailure() called with: code = $code, msg = $msg")
212 | }
213 |
214 | override fun onComplete() {
215 | super.onComplete()
216 | Log.d(TAG, "onButtonUpload onComplete() called")
217 | }
218 | })
219 | }
220 | }
221 |
222 | private fun onButtonDownload() {
223 | /**
224 | * 启动Service进行下载
225 | */
226 | val intent= Intent(this, DownloadService::class.java)
227 | intent.putExtra("url",TKURL.URL_DOWNLOAD)
228 | intent.putExtra("md5","BBFDF5D996224C643402E7B1162ADC27")
229 | startService(intent)
230 | }
231 | }
--------------------------------------------------------------------------------
/RxHttp/src/main/java/io/github/kongpf8848/rxhttp/RxHttp.kt:
--------------------------------------------------------------------------------
1 | package io.github.kongpf8848.rxhttp
2 |
3 | import android.app.Activity
4 | import android.content.Context
5 | import android.text.TextUtils
6 | import androidx.fragment.app.Fragment
7 | import androidx.lifecycle.Lifecycle
8 | import androidx.lifecycle.LifecycleOwner
9 | import com.uber.autodispose.AutoDispose
10 | import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider
11 | import io.github.kongpf8848.rxhttp.bean.DownloadInfo
12 | import io.github.kongpf8848.rxhttp.callback.DownloadCallback
13 | import io.github.kongpf8848.rxhttp.callback.HttpCallback
14 | import io.github.kongpf8848.rxhttp.converter.DownloadConverter
15 | import io.github.kongpf8848.rxhttp.converter.GsonConverter
16 | import io.github.kongpf8848.rxhttp.request.*
17 | import io.github.kongpf8848.rxhttp.util.Md5Util
18 | import io.reactivex.Observable
19 | import io.reactivex.android.schedulers.AndroidSchedulers
20 | import io.reactivex.functions.Function
21 | import io.reactivex.schedulers.Schedulers
22 | import okhttp3.OkHttpClient
23 | import okhttp3.ResponseBody
24 | import retrofit2.Retrofit
25 | import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
26 | import retrofit2.converter.gson.GsonConverterFactory
27 | import retrofit2.converter.scalars.ScalarsConverterFactory
28 | import java.io.File
29 |
30 | class RxHttp private constructor() {
31 |
32 | private object RxHttp {
33 | val holder = RxHttp()
34 | }
35 |
36 | private val okHttpClient: OkHttpClient
37 | private val retrofit: Retrofit
38 | private val httpService: HttpService
39 |
40 | init {
41 | val config = RxHttpConfig.getInstance()
42 | val builder = config.getBuilder()
43 | okHttpClient = builder.build()
44 | retrofit = Retrofit.Builder()
45 | .client(okHttpClient)
46 | .addConverterFactory(ScalarsConverterFactory.create())
47 | .addConverterFactory(GsonConverterFactory.create())
48 | .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
49 | .baseUrl("http://example.com")
50 | .build()
51 | httpService = retrofit.create(HttpService::class.java)
52 | }
53 |
54 | fun getOkHttpClient()=okHttpClient
55 |
56 | //GET请求
57 | fun get(context: Context): GetRequest {
58 | return GetRequest(context)
59 | }
60 |
61 | fun get(activity: Activity): GetRequest {
62 | return GetRequest(activity)
63 | }
64 |
65 | fun get(fragment: Fragment): GetRequest {
66 | return GetRequest(fragment)
67 | }
68 |
69 | //POST请求
70 | fun post(context: Context): PostRequest {
71 | return PostRequest(context)
72 | }
73 |
74 | fun post(activity: Activity): PostRequest {
75 | return PostRequest(activity)
76 | }
77 |
78 | fun post(fragment: Fragment): PostRequest {
79 | return PostRequest(fragment)
80 | }
81 |
82 | //POST FORM请求
83 | fun postForm(context: Context): PostFormRequest {
84 | return PostFormRequest(context)
85 | }
86 |
87 | fun postForm(activity: Activity): PostFormRequest {
88 | return PostFormRequest(activity)
89 | }
90 |
91 | fun postForm(fragment: Fragment): PostFormRequest {
92 | return PostFormRequest(fragment)
93 | }
94 |
95 | //Upload请求
96 | fun upload(context: Context): UploadRequest {
97 | return UploadRequest(context)
98 | }
99 |
100 | fun upload(activity: Activity): UploadRequest {
101 | return UploadRequest(activity)
102 | }
103 |
104 | fun upload(fragment: Fragment): UploadRequest {
105 | return UploadRequest(fragment)
106 | }
107 |
108 | //Download请求
109 | fun download(context: Context): DownloadRequest {
110 | return DownloadRequest(context)
111 | }
112 |
113 | fun download(activity: Activity): DownloadRequest {
114 | return DownloadRequest(activity)
115 | }
116 |
117 | fun download(fragment: Fragment): DownloadRequest {
118 | return DownloadRequest(fragment)
119 | }
120 |
121 | //PUT请求
122 | fun put(context: Context): PutRequest {
123 | return PutRequest(context)
124 | }
125 |
126 | fun put(activity: Activity): PutRequest {
127 | return PutRequest(activity)
128 | }
129 |
130 | fun put(fragment: Fragment): PutRequest {
131 | return PutRequest(fragment)
132 | }
133 |
134 | //DELETE请求
135 | fun delete(context: Context): DeleteRequest {
136 | return DeleteRequest(context)
137 | }
138 |
139 | fun delete(activity: Activity): DeleteRequest {
140 | return DeleteRequest(activity)
141 | }
142 |
143 | fun delete(fragment: Fragment): DeleteRequest {
144 | return DeleteRequest(fragment)
145 | }
146 |
147 | fun enqueue(request: AbsRequest, callback: HttpCallback) {
148 | var observable: Observable? = null
149 | if (request is GetRequest) {
150 | observable = if (request.getParams() != null) {
151 | httpService.get(request.getUrl(), request.getParams()!!)
152 | } else {
153 | httpService.get(request.getUrl())
154 | }
155 | } else if (request is PutRequest) {
156 | observable = httpService.put(request.getUrl(), request.buildRequestBody()!!)
157 | } else if (request is UploadRequest) {
158 | observable = httpService.post(request.getUrl(), request.buildRequestBody()!!)
159 | } else if (request is PostRequest) {
160 | observable = httpService.post(request.getUrl(), request.buildRequestBody()!!)
161 | } else if (request is PostFormRequest) {
162 | observable = if (request.getParams() != null) {
163 | httpService.postForm(request.getUrl(), request.getParams()!!)
164 | } else {
165 | httpService.postForm(request.getUrl())
166 | }
167 | } else if (request is DeleteRequest) {
168 | observable = if (request.getParams() != null) {
169 | httpService.delete(request.getUrl(), request.getParams()!!)
170 | } else {
171 | httpService.delete(request.getUrl())
172 | }
173 | } else if (request is DownloadRequest) {
174 | val file = File(request.dir, request.filename)
175 | val downloadInfo = DownloadInfo(request.getUrl(), request.dir, request.filename)
176 | if (!TextUtils.isEmpty(request.md5)) {
177 | if (file.exists()) {
178 | val fileMd5 = Md5Util.getMD5(file)
179 | if (request.md5.equals(fileMd5, ignoreCase = true)) {
180 | downloadInfo.total = file.length()
181 | downloadInfo.progress = file.length()
182 | callback.onNext(downloadInfo as T)
183 | callback.onComplete()
184 | return
185 | }
186 | }
187 | }
188 | if (request.isBreakpoint) {
189 | observable = Observable.just(request.getUrl())
190 | .flatMap { url ->
191 | val contentLength = getContentLength(url)
192 | var startPosition: Long = 0
193 | if (file.exists()) {
194 | if (contentLength == -1L || file.length() >= contentLength) {
195 | file.delete()
196 | } else {
197 | startPosition = file.length()
198 | }
199 | }
200 | Observable.just(startPosition)
201 | }.flatMap { position -> httpService.download(request.getUrl(), String.format("bytes=%d-", position)) }.subscribeOn(Schedulers.io())
202 | } else {
203 | observable = httpService.download(request.getUrl())
204 | }
205 | }
206 | if (observable != null) {
207 | val observableFinal = observable.map(Function { body ->
208 | if (request is DownloadRequest) {
209 | val downloadConverter: DownloadConverter = DownloadConverter(request, callback as DownloadCallback)
210 | downloadConverter.convert(body, callback.type)
211 | } else {
212 | GsonConverter().convert(body, callback.type)
213 | }
214 | }).retryWhen(RetryWithDelay(RxHttpConfig.getInstance().maxRetries, RxHttpConfig.getInstance().retryDelayMillis))
215 | .subscribeOn(Schedulers.io())
216 | .observeOn(AndroidSchedulers.mainThread())
217 | if (request.getContext() is LifecycleOwner) {
218 | val lifecycleOwner = request.getContext() as LifecycleOwner
219 | observableFinal.`as`(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(lifecycleOwner, Lifecycle.Event.ON_DESTROY)))
220 | .subscribe(HttpObserver(callback, request.getTag()))
221 | } else {
222 | observableFinal.subscribeWith(HttpObserver(callback, request.getTag()))
223 | }
224 | }
225 | }
226 |
227 | @Throws(Exception::class)
228 | private fun getContentLength(url: String): Long {
229 | val response = httpService.head(url).execute()
230 | if (response.isSuccessful) {
231 | val contentLength = response.headers()["Content-Length"]
232 | if (!TextUtils.isEmpty(contentLength)) {
233 | return contentLength!!.toLong()
234 | }
235 | }
236 | return -1
237 | }
238 |
239 | /**
240 | * 取消网络请求,tag为null取消所有网络请求,tag不为null值取消指定的网络请求
241 | */
242 | fun cancelRequest(tag: Any?) {
243 | RxHttpTagManager.getInstance().cancelTag(tag)
244 | }
245 |
246 | companion object {
247 | fun getInstance() = RxHttp.holder
248 | }
249 |
250 | }
--------------------------------------------------------------------------------