diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..ad5dd33 --- /dev/null +++ b/build.gradle @@ -0,0 +1,31 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + ext.kotlin_version = '1.2.51' + ext.anko_version = '0.10.5' + ext.retrofit_version = '2.4.0' + repositories { + google() + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:3.1.3' + classpath 'com.github.dcendents:android-maven-gradle-plugin:2.0' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + jcenter() + maven { url 'https://jitpack.io' } + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..d9ae40f --- /dev/null +++ b/gradle.properties @@ -0,0 +1,13 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx1536m +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7a3265e Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..4dc5cfe --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Wed May 23 15:11:47 CST 2018 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..cccdd3d --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..e95643d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/retrofitLib/.gitignore b/retrofitLib/.gitignore new file mode 100644 index 0000000..3543521 --- /dev/null +++ b/retrofitLib/.gitignore @@ -0,0 +1 @@ +/build diff --git a/retrofitLib/build.gradle b/retrofitLib/build.gradle new file mode 100644 index 0000000..e401382 --- /dev/null +++ b/retrofitLib/build.gradle @@ -0,0 +1,51 @@ +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' +apply plugin: 'com.github.dcendents.android-maven' +group = 'com.github.zeropercenthappy' + +android { + compileSdkVersion 27 + + defaultConfig { + minSdkVersion 19 + targetSdkVersion 27 + versionCode 1 + versionName "1.0" + + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + + implementation 'com.android.support:appcompat-v7:27.1.1' + testImplementation 'junit:junit:4.12' + androidTestImplementation 'com.android.support.test:runner:1.0.2' + androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + implementation "org.jetbrains.anko:anko-common:$anko_version" + implementation 'com.github.zeropercenthappy:ZPHAndroidUtils:1.1.2' + api "com.squareup.retrofit2:retrofit:$retrofit_version" + api "com.squareup.retrofit2:converter-gson:$retrofit_version" + api 'com.squareup.okhttp3:logging-interceptor:3.4.1' +} + +task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' +} + +artifacts { + archives sourcesJar +} \ No newline at end of file diff --git a/retrofitLib/proguard-rules.pro b/retrofitLib/proguard-rules.pro new file mode 100644 index 0000000..6e7ffa9 --- /dev/null +++ b/retrofitLib/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/retrofitLib/src/androidTest/java/com/zeropercenthappy/retrofitutil/ExampleInstrumentedTest.java b/retrofitLib/src/androidTest/java/com/zeropercenthappy/retrofitutil/ExampleInstrumentedTest.java new file mode 100644 index 0000000..02779dd --- /dev/null +++ b/retrofitLib/src/androidTest/java/com/zeropercenthappy/retrofitutil/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package com.zeropercenthappy.retrofitutil; + +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getTargetContext(); + + assertEquals("com.zeropercenthappy.retrofitutil.test", appContext.getPackageName()); + } +} diff --git a/retrofitLib/src/main/AndroidManifest.xml b/retrofitLib/src/main/AndroidManifest.xml new file mode 100644 index 0000000..4deac79 --- /dev/null +++ b/retrofitLib/src/main/AndroidManifest.xml @@ -0,0 +1,2 @@ + diff --git a/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/Config.kt b/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/Config.kt new file mode 100644 index 0000000..5854800 --- /dev/null +++ b/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/Config.kt @@ -0,0 +1,14 @@ +package com.zeropercenthappy.retrofitutil + +import okhttp3.logging.HttpLoggingInterceptor + +object Config { + /** + * true or false + */ + var DEBUG_MODE = false + /** + * [HttpLoggingInterceptor.Level] + */ + var LOG_LEVEL = HttpLoggingInterceptor.Level.BODY +} \ No newline at end of file diff --git a/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/ContentType.kt b/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/ContentType.kt new file mode 100644 index 0000000..c360402 --- /dev/null +++ b/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/ContentType.kt @@ -0,0 +1,17 @@ +package com.zeropercenthappy.retrofitutil + +enum class ContentType(val value: String) { + CONTENT_TYPE("Content-Type"), + TEXT("text/plain"), + IMAGE("image/*"), + JPG("image/jpeg"), + PNG("image/png"), + MP3("audio/mp3"), + WAV("audio/wav"), + WMA("audio/x-ms-wma"), + MP4("video/mpeg4"), + AVI("video/avi"), + WMV("video/x-ms-wmv"), + JSON("application/json") + ; +} \ No newline at end of file diff --git a/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/CookieManager.kt b/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/CookieManager.kt new file mode 100644 index 0000000..b631e1b --- /dev/null +++ b/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/CookieManager.kt @@ -0,0 +1,45 @@ +package com.zeropercenthappy.retrofitutil + +import android.content.Context +import android.text.TextUtils +import retrofit2.Response + +object CookieManager { + const val CONSTANT_SET_COOKIE = "Set-Cookie" + const val CONSTANT_COOKIE = "Cookie" + + fun getCookie(context: Context): String { + context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE).run { + return getString(CONSTANT_COOKIE, "") + } + } + + private fun setCookie(context: Context, cookie: String) { + context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE).edit().run { + putString(CONSTANT_COOKIE, cookie) + apply() + } + } + + fun updateCookie(context: Context, response: Response<*>) { + response.headers()?.get(CONSTANT_SET_COOKIE)?.run { + if (!TextUtils.isEmpty(this)) { + setCookie(context, this) + } + } + } + + fun updateCookie(context: Context, response: okhttp3.Response) { + response.headers().get(CONSTANT_SET_COOKIE)?.run { + if (!TextUtils.isEmpty(this)) { + setCookie(context, this) + } + } + } + + fun updateCookie(context: Context, cookie: String) { + if (TextUtils.isEmpty(cookie)) { + setCookie(context, cookie) + } + } +} \ No newline at end of file diff --git a/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/DefaultInterceptor.kt b/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/DefaultInterceptor.kt new file mode 100644 index 0000000..d1c93d5 --- /dev/null +++ b/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/DefaultInterceptor.kt @@ -0,0 +1,102 @@ +package com.zeropercenthappy.retrofitutil + +import android.content.Context +import android.text.TextUtils +import okhttp3.* + +class DefaultInterceptor(private var context: Context, private val handleCookie: Boolean = true, + private val extraParamMap: Map, + private val extraHeaderMap: Map) : Interceptor { + + override fun intercept(chain: Interceptor.Chain): Response { + var request = chain.request() + //其它额外参数 + if (extraParamMap.isNotEmpty()) { + request = addExtraParam(request) + } + val requestBuilder = request.newBuilder() + //是否需要自动管理Cookie + if (handleCookie) { + val cookie = CookieManager.getCookie(context) + if (!TextUtils.isEmpty(cookie)) { + requestBuilder.addHeader(CookieManager.CONSTANT_COOKIE, cookie) + } + } + //其它自定义Header + for (key in extraHeaderMap.keys) { + val value = extraHeaderMap[key] + if (value != null && value != "") { + requestBuilder.addHeader(key, value) + } + } + + val response = chain.proceed(requestBuilder.build()) + //处理返回的Cookie + CookieManager.updateCookie(context, response) + + return response + } + + private fun addExtraParam(request: Request): Request { + val method = request.method() + when (method) { + "GET", "get" -> { + val httpUrlBuilder = request.url().newBuilder() + for (key in extraParamMap.keys) { + val value = extraParamMap[key] + if (value != null && value != "") { + httpUrlBuilder.addQueryParameter(key, value) + } + } + val newHttpUrl = httpUrlBuilder.build() + return request.newBuilder().url(newHttpUrl).build() + } + "POST", "post" -> { + val requestBody = request.body() + when (requestBody) { + is FormBody -> { + //FormBody + val formBodyBuilder = FormBody.Builder() + //原参数 + for (i in 0 until requestBody.size()) { + formBodyBuilder.addEncoded(requestBody.encodedName(i), requestBody.encodedValue(i)) + } + //新参数 + for (key in extraParamMap.keys) { + val value = extraParamMap[key] + if (value != null && value != "") { + formBodyBuilder.addEncoded(key, value) + } + } + val formBody = formBodyBuilder.build() + return request.newBuilder() + .method(request.method(), formBody) + .build() + } + is MultipartBody -> { + //MultipartBody + val builder = MultipartBody.Builder() + builder.setType(MultipartBody.FORM) + //原参数 + for (part in requestBody.parts()) { + builder.addPart(part) + } + //新参数 + for (key in extraParamMap.keys) { + val value = extraParamMap[key] + if (value != null && value != "") { + builder.addFormDataPart(key, value) + } + } + val multipartBody = builder.build() + return request.newBuilder() + .method(request.method(), multipartBody) + .build() + } + else -> return request + } + } + else -> return request + } + } +} \ No newline at end of file diff --git a/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/OkHttpClientBuilder.kt b/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/OkHttpClientBuilder.kt new file mode 100644 index 0000000..2bc407c --- /dev/null +++ b/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/OkHttpClientBuilder.kt @@ -0,0 +1,28 @@ +package com.zeropercenthappy.retrofitutil + +import android.content.Context +import okhttp3.Interceptor +import okhttp3.OkHttpClient +import okhttp3.logging.HttpLoggingInterceptor + +class OkHttpClientBuilder { + private val interceptorList = arrayListOf() + + fun addInterceptor(interceptor: Interceptor): OkHttpClientBuilder { + interceptorList.add(interceptor) + return this + } + + fun addInterceptors(interceptorList: List): OkHttpClientBuilder { + this.interceptorList.addAll(interceptorList) + return this + } + + fun build(): OkHttpClient { + val builder = OkHttpClient.Builder() + for (interceptor in interceptorList) { + builder.addInterceptor(interceptor) + } + return builder.build() + } +} \ No newline at end of file diff --git a/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/RequestBodyBuilder.kt b/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/RequestBodyBuilder.kt new file mode 100644 index 0000000..bedcff6 --- /dev/null +++ b/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/RequestBodyBuilder.kt @@ -0,0 +1,29 @@ +package com.zeropercenthappy.retrofitutil + +import com.zeropercenthappy.utilslibrary.FileUtils +import okhttp3.MediaType +import okhttp3.MultipartBody +import okhttp3.RequestBody +import java.io.File + +object RequestBodyBuilder { + fun createText(value: String): RequestBody { + return RequestBody.create(MediaType.parse(ContentType.TEXT.value), value) + } + + fun createMultipartBodyPartList(fileMap: Map): List { + val partList = arrayListOf() + for (key in fileMap.keys) { + val file = fileMap[key] + file?.apply { + val mimeType = FileUtils.getFileMimeType(file) + mimeType?.apply { + val requestBody = RequestBody.create(MediaType.parse(mimeType), file) + val part = MultipartBody.Part.createFormData(key, file.name, requestBody) + partList.add(part) + } + } + } + return partList + } +} \ No newline at end of file diff --git a/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/RetrofitBuilder.kt b/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/RetrofitBuilder.kt new file mode 100644 index 0000000..dbc9c4a --- /dev/null +++ b/retrofitLib/src/main/java/com/zeropercenthappy/retrofitutil/RetrofitBuilder.kt @@ -0,0 +1,94 @@ +package com.zeropercenthappy.retrofitutil + +import android.content.Context +import android.text.TextUtils +import okhttp3.Interceptor +import okhttp3.logging.HttpLoggingInterceptor +import retrofit2.Retrofit +import retrofit2.converter.gson.GsonConverterFactory +import java.lang.Exception +import java.util.* + +class RetrofitBuilder { + private var baseUrl: String = "" + private var handleCookie: Boolean = true + private var extraParamMap = TreeMap() + private val extraHeaderMap = TreeMap() + private val extraInterceptorList = arrayListOf() + + fun baseUrl(baseUrl: String): RetrofitBuilder { + this.baseUrl = baseUrl + return this + } + + fun handleCookie(handleCookie: Boolean): RetrofitBuilder { + this.handleCookie = handleCookie + return this + } + + fun addParam(key: String, value: String): RetrofitBuilder { + extraParamMap[key] = value + return this + } + + fun addParams(params: Map): RetrofitBuilder { + for (key in params.keys) { + val value = params[key] + if (value != null && value != "") { + extraParamMap[key] = value + } + } + return this + } + + fun addHeader(key: String, value: String): RetrofitBuilder { + extraHeaderMap[key] = value + return this + } + + fun addHeaders(headers: Map): RetrofitBuilder { + for (key in headers.keys) { + val value = headers[key] + if (value != null && value != "") { + extraHeaderMap[key] = value + } + } + return this + } + + fun addInterceptor(interceptor: Interceptor): RetrofitBuilder { + extraInterceptorList.add(interceptor) + return this + } + + fun addInterceptors(interceptorList: List): RetrofitBuilder { + this.extraInterceptorList.addAll(interceptorList) + return this + } + + fun build(context: Context): Retrofit { + if (TextUtils.isEmpty(baseUrl)) { + throw Exception("base url can not be empty") + } + // 默认Interceptor + val defaultInterceptor = DefaultInterceptor(context.applicationContext, handleCookie, + extraParamMap, extraHeaderMap) + extraInterceptorList.add(0, defaultInterceptor) + // LogInterceptor + if (Config.DEBUG_MODE) { + val loggingInterceptor = HttpLoggingInterceptor() + loggingInterceptor.level = Config.LOG_LEVEL + extraInterceptorList.add(loggingInterceptor) + } + // 构造OkHttpClient + val okHttpClient = OkHttpClientBuilder() + .addInterceptors(extraInterceptorList) + .build() + + return Retrofit.Builder() + .baseUrl(baseUrl) + .addConverterFactory(GsonConverterFactory.create()) + .client(okHttpClient) + .build() + } +} \ No newline at end of file diff --git a/retrofitLib/src/main/res/values/strings.xml b/retrofitLib/src/main/res/values/strings.xml new file mode 100644 index 0000000..eaa11bd --- /dev/null +++ b/retrofitLib/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + RetrofitUtil + diff --git a/retrofitLib/src/test/java/com/zeropercenthappy/retrofitutil/ExampleUnitTest.java b/retrofitLib/src/test/java/com/zeropercenthappy/retrofitutil/ExampleUnitTest.java new file mode 100644 index 0000000..e4b23e8 --- /dev/null +++ b/retrofitLib/src/test/java/com/zeropercenthappy/retrofitutil/ExampleUnitTest.java @@ -0,0 +1,17 @@ +package com.zeropercenthappy.retrofitutil; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Example local unit test, which will execute on the development machine (host). + * + * @see Testing documentation + */ +public class ExampleUnitTest { + @Test + public void addition_isCorrect() { + assertEquals(4, 2 + 2); + } +} \ No newline at end of file diff --git a/sample/.gitignore b/sample/.gitignore new file mode 100644 index 0000000..3543521 --- /dev/null +++ b/sample/.gitignore @@ -0,0 +1 @@ +/build diff --git a/sample/build.gradle b/sample/build.gradle new file mode 100644 index 0000000..fb7da00 --- /dev/null +++ b/sample/build.gradle @@ -0,0 +1,39 @@ +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' +android { + compileSdkVersion 27 + defaultConfig { + applicationId "com.zeropercenthappy.retrofitutilsample" + minSdkVersion 19 + targetSdkVersion 27 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + implementation "org.jetbrains.anko:anko-common:$anko_version" + implementation 'com.android.support:appcompat-v7:27.1.1' + implementation 'com.android.support:design:27.1.1' + implementation 'com.android.support:cardview-v7:27.1.1' + implementation 'com.android.support.constraint:constraint-layout:1.1.2' + testImplementation 'junit:junit:4.12' + androidTestImplementation 'com.android.support.test:runner:1.0.2' + androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' + implementation project(':retrofitLib') + implementation('com.yanzhenjie:album:2.0.2') { + exclude group: 'com.android.support' + } + implementation 'com.github.zeropercenthappy:ZPHAndroidUtils:1.1.2' +} diff --git a/sample/proguard-rules.pro b/sample/proguard-rules.pro new file mode 100644 index 0000000..6e7ffa9 --- /dev/null +++ b/sample/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/sample/src/androidTest/java/com/zeropercenthappy/retrofitutilsample/ExampleInstrumentedTest.kt b/sample/src/androidTest/java/com/zeropercenthappy/retrofitutilsample/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..c89bf39 --- /dev/null +++ b/sample/src/androidTest/java/com/zeropercenthappy/retrofitutilsample/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package com.zeropercenthappy.retrofitutilsample + +import android.support.test.InstrumentationRegistry +import android.support.test.runner.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getTargetContext() + assertEquals("com.zeropercenthappy.retrofitutilsample", appContext.packageName) + } +} diff --git a/sample/src/main/AndroidManifest.xml b/sample/src/main/AndroidManifest.xml new file mode 100644 index 0000000..30e1620 --- /dev/null +++ b/sample/src/main/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/MainActivity.kt b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/MainActivity.kt new file mode 100644 index 0000000..ed0bb45 --- /dev/null +++ b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/MainActivity.kt @@ -0,0 +1,168 @@ +package com.zeropercenthappy.retrofitutilsample + +import android.os.Bundle +import android.support.v7.app.AppCompatActivity +import com.yanzhenjie.album.Album +import com.zeropercenthappy.retrofitutil.Config +import com.zeropercenthappy.retrofitutil.RequestBodyBuilder +import com.zeropercenthappy.retrofitutil.RetrofitBuilder +import com.zeropercenthappy.retrofitutilsample.api.IKalleApi +import com.zeropercenthappy.retrofitutilsample.api.KalleUrl +import com.zeropercenthappy.retrofitutilsample.pojo.* +import com.zeropercenthappy.utilslibrary.CacheUtils +import com.zeropercenthappy.utilslibrary.FileUtils +import kotlinx.android.synthetic.main.activity_main.* +import okhttp3.FormBody +import okhttp3.ResponseBody +import okhttp3.logging.HttpLoggingInterceptor +import retrofit2.Call +import retrofit2.Callback +import retrofit2.Response +import java.io.File +import java.util.* + +class MainActivity : AppCompatActivity() { + + private lateinit var extraTestParamMap: Map + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + Config.DEBUG_MODE = true + Config.LOG_LEVEL = HttpLoggingInterceptor.Level.BODY + + extraTestParamMap = mapOf("atopkey" to "aTopValue", "customKey" to "customValue") + + btn_login.setOnClickListener { login() } + btn_get.setOnClickListener { get() } + btn_post.setOnClickListener { post() } + btn_upload.setOnClickListener { pickImage() } + btn_download.setOnClickListener { download() } + btn_post_json.setOnClickListener { postJson() } + } + + private fun login() { + val retrofit = RetrofitBuilder() + .baseUrl(KalleUrl.BASE_URL) + .addParams(extraTestParamMap) + .build(this) + val kalleApi = retrofit.create(IKalleApi::class.java) + val login = kalleApi.login("guest", "123456") + login.enqueue(object : Callback { + override fun onFailure(call: Call, t: Throwable) { + } + + override fun onResponse(call: Call, response: Response) { + } + }) + } + + private fun get() { + val retrofit = RetrofitBuilder() + .baseUrl(KalleUrl.BASE_URL) + .addParams(extraTestParamMap) + .build(this) + val kalleApi = retrofit.create(IKalleApi::class.java) + val get = kalleApi.get("guest", "25") + get.enqueue(object : Callback { + override fun onFailure(call: Call, t: Throwable) { + } + + override fun onResponse(call: Call, response: Response) { + } + }) + } + + private fun post() { + val builder = FormBody.Builder() + builder.addEncoded("name", "guest") + builder.addEncoded("age", "25") + val retrofit = RetrofitBuilder() + .baseUrl(KalleUrl.BASE_URL) + .build(this) + val formBody = builder.build() + val kalleApi = retrofit.create(IKalleApi::class.java) + val post = kalleApi.post(formBody) + + post.enqueue(object : Callback { + override fun onFailure(call: Call, t: Throwable) { + } + + override fun onResponse(call: Call, response: Response) { + } + }) + } + + private fun pickImage() { + Album.image(this) + .multipleChoice() + .selectCount(3) + .camera(true) + .columnCount(3) + .onResult { _, result -> + val fileMap = TreeMap() + for (i in 0 until result.size) { + fileMap["file${i + 1}"] = File(result[i].path) + } + upload(fileMap) + } + .start() + } + + private fun upload(fileMap: TreeMap) { + val retrofit = RetrofitBuilder() + .baseUrl(KalleUrl.BASE_URL) + .build(this) + val kalleApi = retrofit.create(IKalleApi::class.java) + val name = RequestBodyBuilder.createText("guest") + val age = RequestBodyBuilder.createText("25") + val partList = RequestBodyBuilder.createMultipartBodyPartList(fileMap) + val uploadFile = kalleApi.uploadFile(name, age, partList) + uploadFile.enqueue(object : Callback { + override fun onFailure(call: Call, t: Throwable) { + } + + override fun onResponse(call: Call, response: Response) { + } + }) + } + + private fun download() { + val retrofit = RetrofitBuilder() + .baseUrl(KalleUrl.BASE_URL) + .build(this) + val kalleApi = retrofit.create(IKalleApi::class.java) + val downloadFile = kalleApi.downloadFile("upload/1527220017003e5258758-d4a4-495d-bd07-1eb3a6633f39.jpg") + downloadFile.enqueue(object : Callback { + override fun onFailure(call: Call, t: Throwable) { + + } + + override fun onResponse(call: Call, response: Response) { + val cacheFile = CacheUtils.createFormatedCacheFile(this@MainActivity, "jpg") + if (cacheFile != null && response.body() != null) { + FileUtils.writeFileByIS(cacheFile, response.body()!!.byteStream(), false) + } + } + }) + } + + private fun postJson() { + val retrofit = RetrofitBuilder() + .baseUrl(KalleUrl.BASE_URL) + .build(this) + val kalleApi = retrofit.create(IKalleApi::class.java) + val simpleBean = SimpleBean("guest", "25") + val postJson = kalleApi.postJson(simpleBean) + postJson.enqueue(object : Callback { + override fun onFailure(call: Call, t: Throwable) { + } + + override fun onResponse(call: Call, response: Response) { + val result = response.body()?.string() + } + }) + } + +} diff --git a/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/api/IKalleApi.kt b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/api/IKalleApi.kt new file mode 100644 index 0000000..1f5be02 --- /dev/null +++ b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/api/IKalleApi.kt @@ -0,0 +1,37 @@ +package com.zeropercenthappy.retrofitutilsample.api + +import com.zeropercenthappy.retrofitutilsample.pojo.* +import okhttp3.FormBody +import okhttp3.MultipartBody +import okhttp3.RequestBody +import okhttp3.ResponseBody +import retrofit2.Call +import retrofit2.http.* + +interface IKalleApi { + + @FormUrlEncoded + @POST(KalleUrl.LOGIN) + fun login(@Field("name") name: String, @Field("password") password: String): Call + + @GET(KalleUrl.GET) + fun get(@Query("name") name: String, @Query("age") age: String): Call + +// @POST(KalleUrl.POST) +// @FormUrlEncoded +// fun post(@Field("age") age: String): Call + + @POST(KalleUrl.POST) + fun post(@Body formBody: FormBody): Call + + @Multipart + @POST(KalleUrl.UPLOAD) + fun uploadFile(@Part("name") name: RequestBody, @Part("age") age: RequestBody, @Part partList: List): Call + + @Streaming + @GET + fun downloadFile(@Url fileUrl: String): Call + + @POST(KalleUrl.POST_JSON) + fun postJson(@Body simpleBean: SimpleBean): Call +} \ No newline at end of file diff --git a/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/api/KalleUrl.kt b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/api/KalleUrl.kt new file mode 100644 index 0000000..c0751ed --- /dev/null +++ b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/api/KalleUrl.kt @@ -0,0 +1,11 @@ +package com.zeropercenthappy.retrofitutilsample.api + +object KalleUrl { + const val BASE_URL = "http://kalle.nohttp.net/" + + const val LOGIN = "login" + const val GET = "method/get" + const val POST = "method/post" + const val UPLOAD = "upload/form" + const val POST_JSON = "upload/body/json" +} \ No newline at end of file diff --git a/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/pojo/GetBean.kt b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/pojo/GetBean.kt new file mode 100644 index 0000000..9c25ada --- /dev/null +++ b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/pojo/GetBean.kt @@ -0,0 +1,14 @@ +package com.zeropercenthappy.retrofitutilsample.pojo + +import com.google.gson.annotations.SerializedName + +data class GetBean( + @SerializedName("code") val code: Int = 0, + @SerializedName("data") val data: Data = Data(), + @SerializedName("succeed") val succeed: Boolean = false +) { + data class Data( + @SerializedName("name") val name: String = "", + @SerializedName("age") val age: String = "" + ) +} \ No newline at end of file diff --git a/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/pojo/LoginBean.kt b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/pojo/LoginBean.kt new file mode 100644 index 0000000..7a9451f --- /dev/null +++ b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/pojo/LoginBean.kt @@ -0,0 +1,8 @@ +package com.zeropercenthappy.retrofitutilsample.pojo + +import com.google.gson.annotations.SerializedName + +data class LoginBean( + @SerializedName("code") val code: Int = 0, + @SerializedName("succeed") val succeed: Boolean = false +) \ No newline at end of file diff --git a/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/pojo/PostBean.kt b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/pojo/PostBean.kt new file mode 100644 index 0000000..b6ae423 --- /dev/null +++ b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/pojo/PostBean.kt @@ -0,0 +1,14 @@ +package com.zeropercenthappy.retrofitutilsample.pojo + +import com.google.gson.annotations.SerializedName + +data class PostBean( + @SerializedName("code") val code: Int = 0, + @SerializedName("data") val data: Data = Data(), + @SerializedName("succeed") val succeed: Boolean = false +) { + data class Data( + @SerializedName("name") val name: String = "", + @SerializedName("age") val age: String = "" + ) +} \ No newline at end of file diff --git a/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/pojo/SimpleBean.kt b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/pojo/SimpleBean.kt new file mode 100644 index 0000000..2759eb7 --- /dev/null +++ b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/pojo/SimpleBean.kt @@ -0,0 +1,3 @@ +package com.zeropercenthappy.retrofitutilsample.pojo + +data class SimpleBean(val name: String, val age: String) \ No newline at end of file diff --git a/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/pojo/UploadBean.kt b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/pojo/UploadBean.kt new file mode 100644 index 0000000..054a307 --- /dev/null +++ b/sample/src/main/java/com/zeropercenthappy/retrofitutilsample/pojo/UploadBean.kt @@ -0,0 +1,17 @@ +package com.zeropercenthappy.retrofitutilsample.pojo + +import com.google.gson.annotations.SerializedName + +data class UploadBean( + @SerializedName("code") val code: Int = 0, + @SerializedName("succeed") val succeed: Boolean = false, + @SerializedName("data") val data: Data = Data() +) { + data class Data( + @SerializedName("name") val name: String = "", + @SerializedName("password") val password: String = "", + @SerializedName("file1") val file1: String = "", + @SerializedName("file2") val file2: String = "", + @SerializedName("file3") val file3: String = "" + ) +} \ No newline at end of file diff --git a/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml b/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..ddb26ad --- /dev/null +++ b/sample/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/sample/src/main/res/drawable/ic_launcher_background.xml b/sample/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..3a37cf6 --- /dev/null +++ b/sample/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sample/src/main/res/layout/activity_main.xml b/sample/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..69d0698 --- /dev/null +++ b/sample/src/main/res/layout/activity_main.xml @@ -0,0 +1,57 @@ + + + +