> translateResult) {
41 | this.translateResult = translateResult;
42 | }
43 |
44 | public static class TranslateResultBean {
45 |
46 | public String src;
47 | public String tgt;
48 |
49 | public String getSrc() {
50 | return src;
51 | }
52 |
53 | public void setSrc(String src) {
54 | this.src = src;
55 | }
56 |
57 | public String getTgt() {
58 | return tgt;
59 | }
60 |
61 | public void setTgt(String tgt) {
62 | this.tgt = tgt;
63 | }
64 | }
65 |
66 | }
67 |
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/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/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
11 |
12 |
19 |
20 |
31 |
32 |
--------------------------------------------------------------------------------
/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/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Rxjava_Retrofit
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/example/rxjava_retrofit/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.example.rxjava_retrofit;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | google()
6 | jcenter()
7 |
8 | }
9 | dependencies {
10 | classpath 'com.android.tools.build:gradle:3.3.1'
11 |
12 | // NOTE: Do not place your application dependencies here; they belong
13 | // in the individual module build.gradle files
14 | }
15 | }
16 |
17 | allprojects {
18 | repositories {
19 | google()
20 | jcenter()
21 |
22 | }
23 | }
24 |
25 | task clean(type: Delete) {
26 | delete rootProject.buildDir
27 | }
28 |
--------------------------------------------------------------------------------
/data1.js:
--------------------------------------------------------------------------------
1 | {
2 | "status":200,
3 | "message":"请求成功",
4 | "data":{"id":"1","unique_id":"15033024077728990250","title":"第一条","resource":"http://image.coolapk.com/picture/2017/0821/535189_1503299292_8488.png"}}
5 |
6 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 |
15 |
16 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu May 30 17:37:58 CST 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-4.10.1-all.zip
7 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/okhttp3demo/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/okhttp3demo/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 28
5 |
6 |
7 | defaultConfig {
8 | applicationId "com.example.okhttp3demo"
9 | minSdkVersion 15
10 | targetSdkVersion 28
11 | versionCode 1
12 | versionName "1.0"
13 |
14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
15 |
16 | }
17 |
18 | buildTypes {
19 | release {
20 | minifyEnabled false
21 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
22 | }
23 | }
24 |
25 | }
26 |
27 | dependencies {
28 | implementation fileTree(dir: 'libs', include: ['*.jar'])
29 |
30 | implementation 'com.android.support:appcompat-v7:28.0.0'
31 | implementation 'com.android.support.constraint:constraint-layout:1.1.3'
32 | testImplementation 'junit:junit:4.12'
33 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
34 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
35 | implementation 'com.squareup.okhttp3:okhttp:4.2.0'
36 | }
37 |
--------------------------------------------------------------------------------
/okhttp3demo/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 |
--------------------------------------------------------------------------------
/okhttp3demo/src/androidTest/java/com/example/okhttp3demo/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.example.okhttp3demo;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumented test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.example.okhttp3demo", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/okhttp3demo/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/okhttp3demo/src/main/java/com/example/okhttp3demo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.example.okhttp3demo;
2 |
3 | import android.os.Bundle;
4 | import android.os.Environment;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.text.TextUtils;
7 | import android.util.Log;
8 | import android.view.View;
9 | import android.widget.Toast;
10 |
11 | import org.jetbrains.annotations.NotNull;
12 | import org.jetbrains.annotations.Nullable;
13 |
14 | import java.io.File;
15 | import java.io.FileOutputStream;
16 | import java.io.IOException;
17 | import java.util.HashMap;
18 | import java.util.Map;
19 | import java.util.concurrent.TimeUnit;
20 |
21 | import okhttp3.Call;
22 | import okhttp3.Callback;
23 | import okhttp3.FormBody;
24 | import okhttp3.Headers;
25 | import okhttp3.MediaType;
26 | import okhttp3.MultipartBody;
27 | import okhttp3.OkHttpClient;
28 | import okhttp3.Request;
29 | import okhttp3.RequestBody;
30 | import okhttp3.Response;
31 | import okio.BufferedSink;
32 |
33 | /**
34 | * Request是OKHttp的访问请求,Builder是访问辅助类,Response是OKHttp的请求响应
35 | * Request(请求)
36 | * 每一个HTTP请求中,都应该包含一个URL,一个GET或POST方法,以及Header和其他参数,还可以包含特定内容类型的数据流。
37 | * Responses(响应)
38 | * 响应则包含一个回复代码(200代表成功,404代表未找到),Header和定制可选的body。
39 | * OKHttp
40 | * 简单来说,通过OkHttpClient可以发送一个http请求,并且可以读取该请求的响应,它是一个生产Call的工厂。
41 | * 收益于一个共享的响应缓存/线程池/复用的链接等因素,绝大多数应用使用一个OKHttpClient实例,便可满足整个应用的Http请求
42 | *
43 | * 我的博客:https://blog.csdn.net/m0_37796683
44 | */
45 | public class MainActivity extends AppCompatActivity implements View.OnClickListener {
46 | private static final String TAG = MainActivity.class.getSimpleName();
47 | private OkHttpClient mOkHttpClient;
48 |
49 | @Override
50 | protected void onCreate(Bundle savedInstanceState) {
51 | super.onCreate(savedInstanceState);
52 | setContentView(R.layout.activity_main);
53 |
54 | findViewById(R.id.btn_get_sync).setOnClickListener(this);
55 | findViewById(R.id.btn_get_async).setOnClickListener(this);
56 | findViewById(R.id.btn_post_sync_str).setOnClickListener(this);
57 | findViewById(R.id.btn_post_async_str).setOnClickListener(this);
58 | findViewById(R.id.btn_post_key_value).setOnClickListener(this);
59 | findViewById(R.id.btn_post_key_value_more).setOnClickListener(this);
60 | findViewById(R.id.btn_post_file).setOnClickListener(this);
61 | findViewById(R.id.btn_post_form).setOnClickListener(this);
62 | findViewById(R.id.btn_post_streaming).setOnClickListener(this);
63 | findViewById(R.id.btn_post_multipart).setOnClickListener(this);
64 | findViewById(R.id.btn_header_set_read).setOnClickListener(this);
65 | findViewById(R.id.btn_timeout).setOnClickListener(this);
66 |
67 | //方式一:创建OkHttpClient实例,使用默认构造函数,创建默认配置OkHttpClient(官方建议全局只有一个实例)
68 | mOkHttpClient = new OkHttpClient();
69 |
70 | //方式二:通过new OkHttpClient.Builder() 一步步配置一个OkHttpClient实例
71 | // OkHttpClient httpClient = new OkHttpClient.Builder().connectTimeout(13, TimeUnit.SECONDS).build();
72 |
73 | //方式三:如果要求使用现有的实例,可以通过newBuilder().build()方法进行构造
74 | // OkHttpClient client = mOkHttpClient.newBuilder().build();
75 | }
76 |
77 | @Override
78 | public void onClick(View v) {
79 | switch (v.getId()) {
80 | case R.id.btn_get_sync://get同步
81 | setGetSync();
82 | break;
83 | case R.id.btn_get_async://get异步
84 | setGetAsync();
85 | break;
86 | case R.id.btn_post_sync_str://post同步提交String
87 | setPostSnyc();
88 | break;
89 | case R.id.btn_post_async_str://post异步提交String
90 | setPostAsnyc();
91 | break;
92 | case R.id.btn_post_key_value://post单个键值对
93 | setPostKeyValueOne();
94 | break;
95 | case R.id.btn_post_key_value_more://post多个键值对
96 | setPostKeyValueMore();
97 | break;
98 | case R.id.btn_post_file://post提交文件
99 | setPostFile();
100 | break;
101 | case R.id.btn_post_form://post提交表单
102 | setPostForm();
103 | break;
104 | case R.id.btn_post_streaming://post提交流
105 | setPostStreaming();
106 | break;
107 | case R.id.btn_post_multipart://post提交分块请求
108 | setPostMultiPart();
109 | break;
110 | case R.id.btn_header_set_read://head设置和读取
111 | setAndReadHead();
112 | break;
113 | case R.id.btn_timeout://超时设置
114 | setTimeOuts();
115 | break;
116 | default:
117 | break;
118 | }
119 | }
120 |
121 | /**
122 | * get同步请求
123 | */
124 | private void setGetSync() {
125 | new Thread(new Runnable() {
126 | @Override
127 | public void run() {
128 | //通过Builder辅助类构建请求对象
129 | Request request = new Request.Builder()
130 | .get()//get请求
131 | .url("https://www.baidu.com")//请求地址
132 | .build();//构建
133 |
134 | try {
135 | //通过mOkHttpClient调用请求得到Call
136 | final Call call = mOkHttpClient.newCall(request);
137 | //执行同步请求,获取Response对象
138 | Response response = call.execute();
139 |
140 | if (response.isSuccessful()) {//如果请求成功
141 | String string = response.body().string();
142 | Log.e(TAG, "get同步请求success==" + string);
143 | //响应体的string()对于小文档来说十分方便高效,但是如果响应体太大(超过1M),应避免使用string()方法,
144 | //因为它会把整个文档加载到内存中,对用超多1M的响应body,应该使用流的方式来处理。
145 |
146 | //response.body().bytes();//字节数组类型
147 | //response.body().byteStream();//字节流类型
148 | //response.body().charStream();//字符流类型
149 |
150 | printHeads(response.headers());
151 | } else {
152 | Log.e(TAG, "get同步请求failure==");
153 | }
154 | } catch (IOException e) {
155 | e.printStackTrace();
156 | }
157 | }
158 | }).start();
159 | }
160 |
161 | /**
162 | * get异步请求
163 | */
164 | private void setGetAsync() {
165 | //通过Builder辅助类构建Request对象,链式编程
166 | Request request = new Request.Builder()
167 | .url("https://www.baidu.com")
168 | .get()
169 | .build();
170 |
171 | //异步 onFailure()和onResponse()是在异步线程里执行的,所以如果你在Android把更新UI的操作写在这两个方法里面是会报错的
172 | mOkHttpClient.newCall(request).enqueue(new Callback() {
173 | @Override
174 | public void onFailure(@NotNull Call call, @NotNull IOException e) {
175 | e.printStackTrace();
176 | Log.e(TAG, "get异步响应失败==" + e.toString());
177 | }
178 |
179 | @Override
180 | public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
181 | //主线程中更新UI
182 | runOnUiThread(new Runnable() {
183 | @Override
184 | public void run() {
185 | //TODO 在主线程中更新UI的操作
186 | }
187 | });
188 |
189 | Log.e(TAG, "get异步当前线程,线程id==" + Thread.currentThread().getId());
190 | String result = response.body().string();
191 | Log.e(TAG, "get异步响应成功==" + result);
192 | printHeads(response.headers());
193 | }
194 | });
195 |
196 | Log.e(TAG, "主线程,线程id==" + Thread.currentThread().getId());
197 | }
198 |
199 |
200 | /**
201 | * 打印请求头信息
202 | *
203 | * @param headers 请求头集合
204 | */
205 | private void printHeads(Headers headers) {
206 | if (headers == null) return;
207 | for (int i = 0; i < headers.size(); i++) {
208 | Log.e(TAG, "请求头==" + headers.name(i) + ":" + headers.value(i));
209 | }
210 | }
211 |
212 | /**
213 | * Post同步请求(string),同步的请求实际应用中很少用到,这里就举一个例子
214 | * 提交字符串
215 | */
216 | private void setPostSnyc() {
217 | //构建RequestBody对象,post提交的过程需要将提交的内容封装到一个RequestBody中
218 | //MediaType用于描述Http请求和响应体的内容类型,也就是Content-Type
219 | MediaType mediaType = MediaType.parse("text/plain; charset=utf-8");
220 | RequestBody requestBody = RequestBody.create("提交的内容", mediaType);
221 | final Request request = new Request.Builder()
222 | .post(requestBody)
223 | .url("https://api.github.com/markdown/raw")
224 | .build();
225 |
226 | new Thread(new Runnable() {
227 | @Override
228 | public void run() {
229 | try {
230 | Response response = mOkHttpClient.newCall(request).execute();
231 | if (response.isSuccessful()) {
232 | Log.e(TAG, "Post请求String同步响应success==" + response.body().string());
233 | } else {
234 | Log.e(TAG, "Post请求String同步响应failure==" + response.body().string());
235 | }
236 | } catch (IOException e) {
237 | e.printStackTrace();
238 | Log.e(TAG, "Post请求String同步响应failure==" + e.getMessage());
239 | }
240 | }
241 | }).start();
242 | }
243 |
244 | /**
245 | * Post异步请求(string)
246 | */
247 | private void setPostAsnyc() {
248 | RequestBody requestBody = RequestBody.create("提交内容", MediaType.parse("text/plain; charset=utf-8"));
249 | Request request = new Request.Builder()
250 | .url("https://api.github.com/markdown/raw")
251 | .post(requestBody)
252 | .build();
253 | mOkHttpClient.newCall(request).enqueue(new Callback() {
254 | @Override
255 | public void onFailure(@NotNull Call call, @NotNull IOException e) {
256 | Log.e(TAG, "Post请求String异步响应failure==" + e.getMessage());
257 | }
258 |
259 | @Override
260 | public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
261 | String string = response.body().string();
262 | Log.e(TAG, "Post请求String异步响应success==" + string);
263 | }
264 | });
265 | }
266 |
267 | /**
268 | * Post异步(单个键值对)
269 | */
270 | private void setPostKeyValueOne() {
271 | //提交键值对需要用到FormBody,FormBody继承自RequestBody
272 | FormBody formBody = new FormBody.Builder()
273 | //添加键值对(通多Key-value的形式添加键值对参数)
274 | .add("key", "value")
275 | .build();
276 | final Request request = new Request.Builder()
277 | .post(formBody)
278 | .url("url")
279 | .build();
280 |
281 | mOkHttpClient.newCall(request).enqueue(new Callback() {
282 | @Override
283 | public void onFailure(@NotNull Call call, @NotNull IOException e) {
284 | Log.e(TAG, "Post请求(键值对)异步响应failure==" + e.getMessage());
285 | }
286 |
287 | @Override
288 | public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
289 | String result = response.body().string();
290 | Log.e(TAG, "Post请求(键值对)异步响应Success==" + result);
291 | }
292 | });
293 | }
294 |
295 |
296 | /**
297 | * Post异步(多个键值对)
298 | */
299 | private void setPostKeyValueMore() {
300 | Map map = new HashMap<>();
301 | FormBody.Builder builder = new FormBody.Builder();
302 | if (map != null && !map.isEmpty()) {
303 | for (Map.Entry entry : map.entrySet()) {
304 | builder.add(entry.getKey(), entry.getValue());
305 | }
306 | }
307 |
308 | FormBody formBody = builder.build();
309 | Request request = new Request.Builder()
310 | .url("url")
311 | .post(formBody)
312 | .build();
313 | mOkHttpClient.newCall(request).enqueue(new Callback() {
314 | @Override
315 | public void onFailure(@NotNull Call call, @NotNull IOException e) {
316 | Log.e(TAG, "Post请求(多个键值对)异步响应failure==" + e.getMessage());
317 | }
318 |
319 | @Override
320 | public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
321 | String result = response.body().string();
322 | Log.e(TAG, "Post请求(多个键值对)异步响应Success==" + result);
323 | }
324 | });
325 | }
326 |
327 | /**
328 | * post异步提交文件
329 | */
330 | private void setPostFile() {
331 | File file = getFile("User", "okhttp3.txt", "okhttp提交文件");
332 | if (file == null) {
333 | Toast.makeText(this, "没有此文件", Toast.LENGTH_SHORT).show();
334 | return;
335 | }
336 |
337 | RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), file);
338 | Request request = new Request.Builder()
339 | .post(requestBody)
340 | .url("https://api.github.com/markdown/raw")
341 | .build();
342 | mOkHttpClient.newCall(request).enqueue(new Callback() {
343 | @Override
344 | public void onFailure(@NotNull Call call, @NotNull IOException e) {
345 | Log.e(TAG, "Post请求(文件)异步响应failure==" + e.getMessage());
346 | }
347 |
348 | @Override
349 | public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
350 | String result = response.body().string();
351 | Log.e(TAG, "Post请求(文件)异步响应Success==" + result);
352 | }
353 | });
354 | }
355 |
356 | /**
357 | * post提交表单
358 | */
359 | private void setPostForm() {
360 | //使用FormEncodingBuilder来构建和HTML标签相同效果的请求体,键值对将使用一种HTML兼容形式的URL编码来进行编码
361 | FormBody formBody = new FormBody.Builder()
362 | .add("search", "Jurassic Park")
363 | .build();
364 | Request request = new Request.Builder()
365 | .url("https://en.wikipedia.org/w/index.php")
366 | .post(formBody)
367 | .build();
368 |
369 | mOkHttpClient.newCall(request).enqueue(new Callback() {
370 | @Override
371 | public void onFailure(@NotNull Call call, @NotNull IOException e) {
372 | Log.e(TAG, "Post请求(表单)异步响应failure==" + e.getMessage());
373 | }
374 |
375 | @Override
376 | public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
377 | String result = response.body().string();
378 | Log.e(TAG, "Post请求(表单)异步响应Success==" + result);
379 | }
380 | });
381 | }
382 |
383 | /**
384 | * post方式提交流
385 | */
386 | private void setPostStreaming() {
387 | //以流的方式Post提交请求体,请求体的内容由流写入产生,这里是流直接写入OKIO的BufferedSink。
388 | // 你的程序可能会使用OutputStream, 你可以使用BufferedSink.outputStream()来获取
389 | final MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
390 | //重写RequestBody中的几个方法,将本地数据放入到Http协议的请求体中,然后发送到服务器
391 | final RequestBody requestBody = new RequestBody() {
392 | @Nullable
393 | @Override
394 | public MediaType contentType() {
395 | //返回内容类型
396 | return mediaType;
397 | }
398 |
399 | @Override
400 | public void writeTo(@NotNull BufferedSink bufferedSink) throws IOException {
401 | //输入数据头
402 | bufferedSink.writeUtf8("Numbers\\n");
403 | bufferedSink.writeUtf8("-------\\n");
404 |
405 | //构造数据
406 | for (int i = 2; i < 997; i++) {
407 | bufferedSink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
408 | }
409 | }
410 | };
411 |
412 | final Request request = new Request.Builder()
413 | .url("https://api.github.com/markdown/raw")
414 | .post(requestBody)
415 | .build();
416 |
417 | new Thread(new Runnable() {
418 | @Override
419 | public void run() {
420 | try {
421 | Response response = mOkHttpClient.newCall(request).execute();
422 | if (response.isSuccessful()) {
423 | String result = response.body().toString();
424 | Log.e(TAG, "Post请求(流)异步响应Success==" + result);
425 | } else {
426 | Log.e(TAG, "Post请求(流)异步响应failure==" + response);
427 | throw new IOException("Unexpected code " + response);
428 | }
429 | } catch (IOException e) {
430 | e.printStackTrace();
431 | }
432 | }
433 | }).start();
434 | }
435 |
436 | private String factor(int n) {
437 | for (int i = 2; i < n; i++) {
438 | int x = n / i;
439 | if (x * i == n) {
440 | return factor(x) + "x" + i;
441 | }
442 | }
443 | return Integer.toString(n);
444 | }
445 |
446 | /**
447 | * post异步提交分块请求
448 | */
449 | private void setPostMultiPart() {
450 | //MultipartBuilder可以构建复杂的请求体,与HTML文件上传形式兼容,多块请求头中的每个请求体都是一个亲求体,
451 | // 可以定义自己的请求体,这些请求体可以用来描述这块请求,例如他的Content-Disposition,
452 | // 如果Content-Length和Content-Type可用的话,他们会被自动添加到请求头中
453 | MediaType mediaType = MediaType.parse("image/png");
454 | String IMGUR_CLIENT_ID = "...";
455 | MultipartBody multipartBody = new MultipartBody.Builder()
456 | .setType(MultipartBody.FORM)
457 | .addFormDataPart("title", "Square Logo")
458 | .addFormDataPart("image", "logo-square.png", RequestBody.create(mediaType,
459 | new File("website/static/logo-square.png")))
460 | .build();
461 |
462 | Request request = new Request.Builder()
463 | .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
464 | .url("https://api.imgur.com/3/image")
465 | .post(multipartBody)
466 | .build();
467 |
468 | mOkHttpClient.newCall(request).enqueue(new Callback() {
469 | @Override
470 | public void onFailure(@NotNull Call call, @NotNull IOException e) {
471 | Log.e(TAG, "Post请求(分块)异步响应failure==" + e.getMessage());
472 | }
473 |
474 | @Override
475 | public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
476 | String result = response.body().string();
477 | Log.e(TAG, "Post请求(分块)异步响应Success==" + result);
478 | }
479 | });
480 | }
481 |
482 | /**
483 | * HTTP的头部的设置和读取
484 | */
485 | private void setAndReadHead() {
486 | //HTTP头部的数据结构是Map>类型,也就是说,对于每个HTTP的头,可能有多个值,
487 | // 但是大部分的HTTP头只有一个值,只有少部分HTTP头允许多个值,至于name的取值说明请参考:http://tools.jb51.net/table/http_header
488 | //OKHTTP的处理方式是:
489 | //使用header(name, value)来设置HTTP头的唯一值, 如果请求中已经存在响应的信息那么直接替换掉
490 | //使用addHeader(name, value)来补充新值,如果请求头中已经存在name的name-value, 那么还会继续添加,请求头中便会存在多个name相同value不同的“键值对”
491 | //使用header(name, value)读取唯一值或多个值的最后一个值
492 | //使用headers(name)获取所有值
493 |
494 | Request request = new Request.Builder()
495 | .url("https://api.github.com/repos/square/okhttp/issues")
496 | .header("User-Agent", "OkHttp Headers.java")//设置唯一值
497 | .addHeader("Server", "application/json; q=0.5")//设置新值
498 | .addHeader("Server", "application/vnd.github.v3+json")//设置新值
499 | .build();
500 |
501 | mOkHttpClient.newCall(request).enqueue(new Callback() {
502 | @Override
503 | public void onFailure(@NotNull Call call, @NotNull IOException e) {
504 | Log.e(TAG, "Post请求(HTTP头)异步响应failure==" + e.getMessage());
505 | }
506 |
507 | @Override
508 | public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
509 | Log.e(TAG, "header:Date==" + response.header("Date"));
510 | Log.e(TAG, "header:User-Agent==" + response.header("User-Agent"));
511 | Log.e(TAG, "headers:Server==" + response.headers("Server"));
512 | Log.e(TAG, "headers:Vary==" + response.headers("Vary"));
513 |
514 | Log.e(TAG, "Post请求(HTTP头)异步响应Success==" + response.body().string());
515 | }
516 | });
517 | }
518 |
519 |
520 | /**
521 | * 超时测试
522 | *
523 | * @throws IOException
524 | */
525 | private void setTimeOuts() {
526 | //1.构建OkHttpClient实例
527 | final OkHttpClient okHttpClient = new OkHttpClient.Builder()
528 | .connectTimeout(2, TimeUnit.SECONDS)//链接超时为2秒,单位为秒
529 | .writeTimeout(2, TimeUnit.SECONDS)//写入超时
530 | .readTimeout(2, TimeUnit.SECONDS)//读取超时
531 | .build();
532 |
533 | //2.通过Builder辅助类构建请求对象
534 | final Request request = new Request.Builder()
535 | .url("http://httpbin.org/delay/10")//URL地址
536 | .build();//构建
537 |
538 | //创建线程,在子线程中运行
539 | new Thread(new Runnable() {
540 | @Override
541 | public void run() {
542 | try {
543 | //3.通过mOkHttpClient调用请求得到Call
544 | final Call call = okHttpClient.newCall(request);
545 | //4.执行同步请求,获取响应体Response对象
546 | Response response = call.execute();
547 | Log.e(TAG, "请求(超时)==" + response);
548 | } catch (IOException e) {
549 | e.printStackTrace();
550 | Log.e(TAG, "请求(超时)==" + e.toString());
551 | }
552 | }
553 | }).start();
554 | }
555 |
556 | /**
557 | * 创建文件
558 | *
559 | * @param filePath 文件路径
560 | * @param fileName 文件名
561 | * @param content 文件内容
562 | * @return 文件
563 | */
564 | private File getFile(String filePath, String fileName, String content) {
565 | if (filePath == null || filePath.length() == 0 || fileName == null || fileName.length() == 0) {
566 | return null;
567 | }
568 |
569 | //判断是否有SD卡
570 | if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
571 | Toast.makeText(this, "请插入SD卡", Toast.LENGTH_SHORT).show();
572 | return null;
573 | }
574 |
575 | //创建文件夹
576 | File sdCardDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filePath);
577 | if (!sdCardDir.exists()) {
578 | if (!sdCardDir.mkdirs()) {
579 | try {
580 | sdCardDir.createNewFile();
581 | } catch (Exception e) {
582 | e.printStackTrace();
583 | }
584 | }
585 | }
586 |
587 | //创建.txt文件
588 | File saveFile = new File(sdCardDir, fileName);
589 | try {
590 | if (!saveFile.exists()) {
591 | saveFile.createNewFile();
592 | }
593 | } catch (Exception e) {
594 | e.printStackTrace();
595 | }
596 |
597 | //文件写入数据
598 | if (!TextUtils.isEmpty(content)) {
599 | FileOutputStream outStream = null;
600 | try {
601 | outStream = new FileOutputStream(saveFile);
602 | outStream.write(content.getBytes());
603 | outStream.close();
604 | } catch (IOException e) {
605 | e.printStackTrace();
606 | }
607 | }
608 | return saveFile;
609 | }
610 | }
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/okhttp3demo/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 |
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
11 |
12 |
18 |
19 |
27 |
28 |
36 |
37 |
45 |
46 |
54 |
55 |
63 |
64 |
72 |
73 |
81 |
82 |
90 |
91 |
99 |
100 |
108 |
109 |
118 |
119 |
120 |
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/okhttp3demo/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/okhttp3demo/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/okhttp3demo/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/okhttp3demo/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/okhttp3demo/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/okhttp3demo/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/okhttp3demo/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/okhttp3demo/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/okhttp3demo/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/suming77/Rxjava_Retrofit/d979d8ec40c6fc6cd2f74e252b6ae25e48c656ea/okhttp3demo/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | OKHttp3Demo
3 |
4 |
--------------------------------------------------------------------------------
/okhttp3demo/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/okhttp3demo/src/test/java/com/example/okhttp3demo/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.example.okhttp3demo;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/rxjava2demo/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/rxjava2demo/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 28
5 |
6 |
7 | defaultConfig {
8 | applicationId "com.example.rxjava2demo"
9 | minSdkVersion 15
10 | targetSdkVersion 28
11 | versionCode 1
12 | versionName "1.0"
13 |
14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
15 |
16 | }
17 |
18 | buildTypes {
19 | release {
20 | minifyEnabled false
21 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
22 | }
23 | }
24 |
25 | }
26 |
27 | dependencies {
28 | implementation fileTree(dir: 'libs', include: ['*.jar'])
29 |
30 | implementation 'com.android.support:appcompat-v7:28.0.0'
31 | implementation 'com.android.support.constraint:constraint-layout:1.1.3'
32 | testImplementation 'junit:junit:4.12'
33 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
34 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
35 | implementation 'io.reactivex.rxjava2:rxjava:2.0.4'
36 | implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
37 | }
38 |
--------------------------------------------------------------------------------
/rxjava2demo/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 |
--------------------------------------------------------------------------------
/rxjava2demo/src/androidTest/java/com/example/rxjava2demo/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.example.rxjava2demo;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumented test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.example.rxjava2demo", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/rxjava2demo/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/rxjava2demo/src/main/java/com/example/rxjava2demo/Goods.java:
--------------------------------------------------------------------------------
1 | package com.example.rxjava2demo;
2 |
3 | /**
4 | * @创建者 mingyan.su
5 | * @创建时间 2019/10/16 21:09
6 | * @类描述 ${TODO}
7 | */
8 | public class Goods {
9 | private String name;
10 |
11 | public Goods(String name) {
12 | this.name = name;
13 | }
14 |
15 | public String getName() {
16 | return name;
17 | }
18 |
19 | public void setName(String name) {
20 | this.name = name;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/rxjava2demo/src/main/java/com/example/rxjava2demo/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.example.rxjava2demo;
2 |
3 | import android.content.Intent;
4 | import android.os.Bundle;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.util.Log;
7 | import android.view.View;
8 |
9 | import java.text.SimpleDateFormat;
10 | import java.util.ArrayList;
11 | import java.util.List;
12 | import java.util.concurrent.Callable;
13 | import java.util.concurrent.TimeUnit;
14 |
15 | import io.reactivex.Observable;
16 | import io.reactivex.ObservableEmitter;
17 | import io.reactivex.ObservableOnSubscribe;
18 | import io.reactivex.ObservableSource;
19 | import io.reactivex.Observer;
20 | import io.reactivex.android.schedulers.AndroidSchedulers;
21 | import io.reactivex.disposables.Disposable;
22 | import io.reactivex.functions.Predicate;
23 | import io.reactivex.schedulers.Schedulers;
24 |
25 | /**
26 | * RxJava2的简单使用(一)
27 | * 我的博客:https://blog.csdn.net/m0_37796683
28 | */
29 | public class MainActivity extends AppCompatActivity implements View.OnClickListener {
30 | private static final String TAG = MainActivity.class.getSimpleName();
31 |
32 | @Override
33 | protected void onCreate(Bundle savedInstanceState) {
34 | super.onCreate(savedInstanceState);
35 | setContentView(R.layout.activity_main);
36 | Log.e(TAG, "主线程==id:" + Thread.currentThread().getId());
37 |
38 |
39 | findViewById(R.id.btn_rxjava2_02).setOnClickListener(this);
40 | findViewById(R.id.btn_rxjava2_03).setOnClickListener(this);
41 | findViewById(R.id.btn_rxjava2_04).setOnClickListener(this);
42 |
43 | findViewById(R.id.btn_create).setOnClickListener(this);
44 | findViewById(R.id.btn_empty).setOnClickListener(this);
45 | findViewById(R.id.btn_error).setOnClickListener(this);
46 | findViewById(R.id.btn_never).setOnClickListener(this);
47 | findViewById(R.id.btn_just).setOnClickListener(this);
48 | findViewById(R.id.btn_fromArray).setOnClickListener(this);
49 | findViewById(R.id.btn_fromIterable).setOnClickListener(this);
50 | findViewById(R.id.btn_defer).setOnClickListener(this);
51 | findViewById(R.id.btn_timer).setOnClickListener(this);
52 | findViewById(R.id.btn_interval).setOnClickListener(this);
53 | findViewById(R.id.btn_intervalRange).setOnClickListener(this);
54 | findViewById(R.id.btn_range).setOnClickListener(this);
55 |
56 | //观察者不对被观察者发送的事件做出响应(但是被观察者还可以继续发送事件)
57 | //public final Disposable subscribe()
58 |
59 | //观察者对被观察者发送的任何事件都做出响应
60 | //public final void subscribe(Observer super T> observer)
61 |
62 | //表示观察者只对被观察者发送的Next事件做出响应
63 | //public final Disposable subscribe(Consumer super T> onNext)
64 |
65 | //表示观察者只对被观察者发送的Next & Error事件做出响应
66 | //public final Disposable subscribe(Consumer super T> onNext, Consumer super Throwable> onError)
67 |
68 | //表示观察者只对被观察者发送的Next & Error & Complete事件做出响应
69 | //public final Disposable subscribe(Consumer super T> onNext, Consumer super Throwable> onError,
70 | //Action onComplete)
71 |
72 | //表示观察者只对被观察者发送的Next & Error & Complete & onSubscribe事件做出响应
73 | //public final Disposable subscribe(Consumer super T> onNext, Consumer super Throwable> onError,
74 | //Action onComplete, Consumer super Disposable> onSubscribe)
75 | }
76 |
77 | @Override
78 | public void onClick(View v) {
79 | switch (v.getId()) {
80 | case R.id.btn_rxjava2_02://RxJava2的简单使用(二)
81 | startActivity(new Intent(this, RxJavaActivity02.class));
82 | break;
83 | case R.id.btn_rxjava2_03://RxJava2的简单使用(三)
84 | startActivity(new Intent(this, RxJavaActivity03.class));
85 | break;
86 | case R.id.btn_rxjava2_04://RxJava2的简单使用(四)
87 | startActivity(new Intent(this, RxJavaActivity04.class));
88 | break;
89 | case R.id.btn_create://
90 | create();
91 | break;
92 | case R.id.btn_empty://
93 | empty();
94 | break;
95 | case R.id.btn_error://
96 | error();
97 | break;
98 | case R.id.btn_never://
99 | never();
100 | break;
101 | case R.id.btn_just://
102 | just();
103 | break;
104 | case R.id.btn_fromArray://
105 | fromArray();
106 | break;
107 | case R.id.btn_fromIterable://
108 | fromIterable();
109 | break;
110 | case R.id.btn_defer://
111 | defer();
112 | break;
113 | case R.id.btn_timer://
114 | timer();
115 | break;
116 | case R.id.btn_interval://
117 | interval();
118 | break;
119 | case R.id.btn_intervalRange://
120 | intervalRange();
121 | break;
122 | case R.id.btn_range://
123 | range();
124 | break;
125 | default:
126 | break;
127 | }
128 | }
129 |
130 | /**
131 | * 基本创建
132 | * Observable.create
133 | * RxJava创建被观察者对象的最基本操作符
134 | */
135 | private void create() {
136 | //1、创建被观察者Observable
137 | //当 Observable 被订阅时,OnSubscribe 的 call() 方法会自动被调用,即事件序列就会依照设定依次被触发
138 | Observable observable = Observable.create(new ObservableOnSubscribe() {
139 | @Override
140 | public void subscribe(ObservableEmitter emitter) throws Exception {
141 | // 通过 ObservableEmitter类对象产生事件并通知观察者
142 | //即观察者会依次调用对应事件的复写方法从而响应事件
143 | try {
144 | if (!emitter.isDisposed()) {
145 | emitter.onNext("RxJava:e.onNext== 第一次");
146 | emitter.onNext("RxJava:e.onNext== 第二次");
147 | emitter.onNext("RxJava:e.onNext== 第三次");
148 | Log.e(TAG, "subscribe()==执行事件的线程==id:" + Thread.currentThread().getId());
149 | emitter.onComplete();
150 | }
151 | } catch (Exception e) {
152 | emitter.onError(e);
153 | }
154 | }
155 | }).subscribeOn(Schedulers.io())//指定subscribe()(发射事件的线程)在IO线程()
156 | .observeOn(AndroidSchedulers.mainThread());//指定订阅者接收事件的线程在主线程;
157 |
158 | //2、创建观察者Observer 并且定义响应事件
159 | Observer observer = new Observer() {
160 | //默认最先复写onSubscribe()
161 | @Override
162 | public void onSubscribe(Disposable d) {
163 | Log.e(TAG, "onSubscribe == 订阅");
164 | }
165 |
166 | @Override
167 | public void onNext(String s) {
168 | Log.e(TAG, "onNext == " + s);
169 | Log.e(TAG, "onNext()==回调事件的线程==id:" + Thread.currentThread().getId());
170 | }
171 |
172 | @Override
173 | public void onError(Throwable e) {
174 | Log.e(TAG, "onError == " + e.getMessage());
175 | }
176 |
177 | @Override
178 | public void onComplete() {
179 | Log.e(TAG, "onComplete == ");
180 | }
181 | };
182 |
183 | //3、订阅(观察者观察被观察者)
184 | observable.subscribe(observer);
185 | }
186 |
187 | private void empty() {
188 | //快速创建被观察者对象,仅发送onComplete()事件,直接通知完成。
189 | Observable.empty()
190 | .subscribe(new Observer