├── .gitignore
├── .idea
├── compiler.xml
├── copyright
│ └── profiles_settings.xml
├── encodings.xml
├── gradle.xml
├── misc.xml
├── modules.xml
├── runConfigurations.xml
└── vcs.xml
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── xj
│ │ └── networklibrary
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── xj
│ │ │ └── networklibrary
│ │ │ └── MainActivity.java
│ └── res
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── xj
│ └── networklibrary
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── library
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── xj
│ │ └── network
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── xj
│ │ │ └── network
│ │ │ ├── HttpException.java
│ │ │ ├── IResponseListener.java
│ │ │ ├── LogUtil.java
│ │ │ ├── NetManger.java
│ │ │ ├── NetRequest.java
│ │ │ ├── NetUtils.java
│ │ │ ├── NetworkOption.java
│ │ │ ├── Utils.java
│ │ │ ├── mtOkHttp
│ │ │ ├── LoggingInterceptor.java
│ │ │ ├── OKHttpRequest.java
│ │ │ └── OKHttpUtils.java
│ │ │ ├── okhttp
│ │ │ ├── HttpsUtils.java
│ │ │ ├── JsonUtils.java
│ │ │ ├── client
│ │ │ │ └── CommonOkhttpClient.java
│ │ │ ├── exception
│ │ │ │ └── OkHttpException.java
│ │ │ ├── listener
│ │ │ │ ├── DisposeDataHandle.java
│ │ │ │ ├── DisposeDataListener.java
│ │ │ │ ├── DisposeDownloadListener.java
│ │ │ │ └── DisposeHandleCookieListener.java
│ │ │ ├── request
│ │ │ │ ├── CommonRequest.java
│ │ │ │ └── RequestParams.java
│ │ │ └── response
│ │ │ │ ├── CommonFileCallback.java
│ │ │ │ └── CommonJsonCallback.java
│ │ │ └── volley
│ │ │ └── VolleyRequest.java
│ └── res
│ │ └── values
│ │ └── strings.xml
│ └── test
│ └── java
│ └── xj
│ └── network
│ └── ExampleUnitTest.java
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 | /svip-club/
11 | /gradle.properties
12 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
19 |
20 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | 1.7
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 26
5 | buildToolsVersion "26.0.1"
6 | defaultConfig {
7 | applicationId "xj.networklibrary"
8 | minSdkVersion 21
9 | targetSdkVersion 26
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(include: ['*.jar'], dir: 'libs')
24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
25 | exclude group: 'com.android.support', module: 'support-annotations'
26 | })
27 | compile 'com.android.support:appcompat-v7:26.+'
28 | compile 'com.android.support.constraint:constraint-layout:1.0.2'
29 | testCompile 'junit:junit:4.12'
30 | compile project(':library')
31 | }
32 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in C:\Android\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/xj/networklibrary/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package xj.networklibrary;
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 | * Instrumentation 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() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("xj.networklibrary", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/app/src/main/java/xj/networklibrary/MainActivity.java:
--------------------------------------------------------------------------------
1 | package xj.networklibrary;
2 |
3 | import android.os.Bundle;
4 | import android.os.Looper;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.util.Log;
7 | import android.view.View;
8 | import android.widget.Button;
9 | import android.widget.TextView;
10 |
11 | import java.util.HashMap;
12 |
13 | import xj.network.HttpException;
14 | import xj.network.IResponseListener;
15 | import xj.network.LogUtil;
16 | import xj.network.NetManger;
17 | import xj.network.mtOkHttp.OKHttpRequest;
18 | import xj.network.volley.VolleyRequest;
19 |
20 | public class MainActivity extends AppCompatActivity {
21 |
22 | private static final String TAG = "MainActivity";
23 |
24 | String url = "http://route.showapi.com/109-34";
25 | private Button mBtnGet;
26 | private Button mBtnPush;
27 | private TextView mTv;
28 | private HashMap mMap;
29 |
30 | @Override
31 | protected void onCreate(Bundle savedInstanceState) {
32 | super.onCreate(savedInstanceState);
33 | setContentView(R.layout.activity_main);
34 | initView();
35 | NetManger.init(this);
36 | LogUtil.init(this);
37 | mMap = new HashMap<>();
38 | mMap.put("showapi_appid","29571");
39 | mMap.put("showapi_sign","5bf00910e04a46998f6979f6da400f1e");
40 | }
41 |
42 | private void initView() {
43 | mBtnGet = (Button) findViewById(R.id.btn_get);
44 | mBtnPush = (Button) findViewById(R.id.btn_push);
45 | mTv = (TextView) findViewById(R.id.tv);
46 | mBtnGet.setOnClickListener(new View.OnClickListener() {
47 | @Override
48 | public void onClick(View v) {
49 | NetManger.getRequest(OKHttpRequest.class).doGet(url, mMap, new IResponseListener() {
50 | @Override
51 | public void onResponse(String response) {
52 | mTv.setText("GET 请求\n"+response);
53 | boolean b = Looper.getMainLooper() == Looper.myLooper();
54 | LogUtil.i(TAG,"onResponse: b="+b);
55 | LogUtil.i(TAG,"onResponse: response ="+response);
56 | }
57 |
58 | @Override
59 | public void onFail(HttpException httpException) {
60 | Log.i(TAG, "onFail: httpException=" +httpException.toString());
61 | }
62 | });
63 | }
64 | });
65 | mBtnPush.setOnClickListener(new View.OnClickListener() {
66 | @Override
67 | public void onClick(View v) {
68 | NetManger.getRequest(VolleyRequest.class).doPost(url, mMap, new IResponseListener() {
69 | @Override
70 | public void onResponse(String response) {
71 | mTv.setText("post 请求\n"+response);
72 | LogUtil.i(TAG,"onResponse: response ="+response);
73 | }
74 |
75 | @Override
76 | public void onFail(HttpException httpException) {
77 | Log.i(TAG, "onFail: httpException=" +httpException.toString());
78 | }
79 | });
80 | }
81 | });
82 |
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
14 |
15 |
21 |
22 |
28 |
29 |
35 |
36 |
37 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gdutxiaoxu/Networklibrary/3d224d91a57f965e20d67302da1dc4504f309b4c/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gdutxiaoxu/Networklibrary/3d224d91a57f965e20d67302da1dc4504f309b4c/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gdutxiaoxu/Networklibrary/3d224d91a57f965e20d67302da1dc4504f309b4c/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gdutxiaoxu/Networklibrary/3d224d91a57f965e20d67302da1dc4504f309b4c/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gdutxiaoxu/Networklibrary/3d224d91a57f965e20d67302da1dc4504f309b4c/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gdutxiaoxu/Networklibrary/3d224d91a57f965e20d67302da1dc4504f309b4c/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gdutxiaoxu/Networklibrary/3d224d91a57f965e20d67302da1dc4504f309b4c/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gdutxiaoxu/Networklibrary/3d224d91a57f965e20d67302da1dc4504f309b4c/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gdutxiaoxu/Networklibrary/3d224d91a57f965e20d67302da1dc4504f309b4c/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gdutxiaoxu/Networklibrary/3d224d91a57f965e20d67302da1dc4504f309b4c/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Networklibrary
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/xj/networklibrary/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package xj.networklibrary;
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() throws Exception {
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 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.3.3'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | jcenter()
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gdutxiaoxu/Networklibrary/3d224d91a57f965e20d67302da1dc4504f309b4c/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Nov 15 14:49:36 CST 2017
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-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/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 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
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 Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 26
5 | buildToolsVersion "26.0.1"
6 |
7 | defaultConfig {
8 | minSdkVersion 21
9 | targetSdkVersion 26
10 | versionCode 1
11 | versionName "1.0"
12 |
13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14 |
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | }
23 |
24 | dependencies {
25 | compile fileTree(dir: 'libs', include: ['*.jar'])
26 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
27 | exclude group: 'com.android.support', module: 'support-annotations'
28 | })
29 | compile 'com.android.support:appcompat-v7:26.+'
30 | testCompile 'junit:junit:4.12'
31 | compile 'com.mcxiaoke.volley:library:1.0.19'
32 | compile 'com.squareup.okhttp3:okhttp:3.9.0'
33 | compile 'com.orhanobut:logger:2.1.1'
34 | compile 'com.google.code.gson:gson:2.8.0'
35 | }
36 |
--------------------------------------------------------------------------------
/library/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in C:\Android\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/library/src/androidTest/java/xj/network/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package xj.network;
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 | * Instrumentation 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() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("xj.network.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
7 |
8 |
9 |
10 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/HttpException.java:
--------------------------------------------------------------------------------
1 | package xj.network;
2 |
3 | /**
4 | * @author meitu.xujun on 2017/4/8 17:26
5 | * @version 0.1
6 | */
7 |
8 | public class HttpException {
9 |
10 | public int code;
11 | public Exception e;
12 | public String errMsg;
13 |
14 | public HttpException() {
15 | }
16 |
17 | public HttpException(int code, Exception e, String errMsg) {
18 | this.code = code;
19 | this.e = e;
20 | this.errMsg = errMsg;
21 | }
22 |
23 | @Override
24 | public String toString() {
25 | return "HttpException{" +
26 | "code=" + code +
27 | ", e=" + e +
28 | ", errMsg='" + errMsg + '\'' +
29 | '}';
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/IResponseListener.java:
--------------------------------------------------------------------------------
1 | package xj.network;
2 |
3 | /**
4 | * @author meitu.xujun on 2017/3/22 16:10
5 | * @version 0.1
6 | */
7 |
8 | public interface IResponseListener {
9 |
10 | void onResponse(String response);
11 | void onFail(HttpException httpException);
12 | }
13 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/LogUtil.java:
--------------------------------------------------------------------------------
1 | package xj.network;
2 |
3 | import android.content.Context;
4 |
5 | import com.orhanobut.logger.AndroidLogAdapter;
6 | import com.orhanobut.logger.FormatStrategy;
7 | import com.orhanobut.logger.Logger;
8 | import com.orhanobut.logger.PrettyFormatStrategy;
9 |
10 | import java.io.BufferedWriter;
11 | import java.io.File;
12 | import java.io.FileWriter;
13 | import java.io.IOException;
14 | import java.text.SimpleDateFormat;
15 | import java.util.Date;
16 |
17 | /**
18 | * @author meitu.xujun on 2017/9/6 9:56
19 | * @version 0.1
20 | */
21 | public class LogUtil {
22 |
23 | private static final String TAG = "MEITU_SVIP";
24 |
25 | // public static String cacheDir = "";
26 | public static String cacheDir = "/sdcard";
27 | public static String PATH = cacheDir + "/Log";
28 | public static final String LOG_FILE_NAME = "log.txt";
29 |
30 | /**
31 | * 是否写入日志文件
32 | */
33 | public static final boolean LOG_WRITE_TO_FILE = false;
34 |
35 | public static final boolean isIShow = true;
36 | public static final boolean isDShow = true;
37 | public static final boolean isWShow = true;
38 | public static final boolean isEShow = true;
39 | public static final boolean isJSONShow = true;
40 |
41 | public static void init(Context context) {
42 | Context applicationContext = context.getApplicationContext();
43 | if (applicationContext.getExternalCacheDir() != null && isExistSDCard()) {
44 | cacheDir = applicationContext.getExternalCacheDir().toString();
45 |
46 | } else {
47 | cacheDir = applicationContext.getCacheDir().toString();
48 | }
49 | PATH = cacheDir + "/Log";
50 | FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
51 | .showThreadInfo(false) // (Optional) Whether to show thread info or not. Default true
52 | .methodCount(4) // (Optional) How many method line to show. Default 2
53 | .methodOffset(5) // (Optional) Hides internal method calls up to offset. Default 5
54 | // (Optional) Changes the log strategy to print out. Default LogCat
55 | .tag(TAG) // (Optional) Global mTag for every log. Default PRETTY_LOGGER
56 | .build();
57 |
58 | Logger.addLogAdapter(new AndroidLogAdapter());
59 |
60 | }
61 |
62 | public static final void json(String msg) {
63 | json(TAG,msg);
64 | }
65 |
66 | /**
67 | * 错误信息
68 | *
69 | * @param TAG
70 | * @param msg
71 | */
72 | public final static void e(String TAG, String msg) {
73 | if (isEShow) {
74 | Logger.t(generateTag(TAG)).e(msg);
75 |
76 | }
77 | if (LOG_WRITE_TO_FILE) writeLogtoFile("e", generateTag(TAG), msg);
78 |
79 | }
80 |
81 | public final static void e(String msg) {
82 | e(TAG, msg);
83 |
84 |
85 | }
86 |
87 | /**
88 | * 警告信息
89 | *
90 | * @param TAG
91 | * @param msg
92 | */
93 | public final static void w(String TAG, String msg) {
94 | if (isWShow) {
95 | Logger.t(generateTag(TAG)).w(msg);
96 | }
97 |
98 | if (LOG_WRITE_TO_FILE) writeLogtoFile("w", generateTag(TAG), msg);
99 | }
100 |
101 | public final static void w(String msg) {
102 | w(TAG, msg);
103 | }
104 |
105 | /**
106 | * 调试信息
107 | *
108 | * @param TAG
109 | * @param msg
110 | */
111 | public final static void d(String TAG, String msg) {
112 | if (isDShow) {
113 | Logger.t(generateTag(TAG)).d(msg);
114 | }
115 |
116 | if (LOG_WRITE_TO_FILE) writeLogtoFile("d", TAG, msg);
117 | }
118 |
119 | public final static void d(String msg) {
120 | d(TAG, msg);
121 | }
122 |
123 | /**
124 | * 提示信息
125 | *
126 | * @param TAG
127 | * @param msg
128 | */
129 | public final static void i(String TAG, String msg) {
130 |
131 |
132 | if (isIShow) {
133 | Logger.t(generateTag(TAG)).i(msg);
134 | }
135 |
136 |
137 | if (LOG_WRITE_TO_FILE) writeLogtoFile("i", TAG, msg);
138 | }
139 |
140 |
141 |
142 | public final static void json(String TAG, String msg) {
143 |
144 |
145 | if (isJSONShow) {
146 | Logger.t(generateTag(TAG)).json(msg);
147 | }
148 |
149 |
150 | if (LOG_WRITE_TO_FILE) writeLogtoFile("json", TAG, msg);
151 | }
152 |
153 | public final static void i(String msg) {
154 | i(TAG, msg);
155 | }
156 |
157 | /**
158 | * 写入日志到文件中
159 | *
160 | * @param logType
161 | * @param tag
162 | * @param msg
163 | */
164 | private static void writeLogtoFile(String logType, String tag, String msg) {
165 | isExist(PATH);
166 | //isDel();
167 | String needWriteMessage = "\r\n" + getNowYMDHMSTime() + "\r\n" + logType + " "
168 | + generateTag(tag) + "\r\n" + msg;
169 | File parent = new File(PATH);
170 | if (!parent.exists()) {
171 | parent.mkdirs();
172 | }
173 | File file = new File(PATH, LOG_FILE_NAME);
174 | try {
175 | FileWriter filerWriter = new FileWriter(file, true);
176 | BufferedWriter bufWriter = new BufferedWriter(filerWriter);
177 | bufWriter.write(needWriteMessage);
178 | bufWriter.newLine();
179 | bufWriter.close();
180 | filerWriter.close();
181 | } catch (IOException e) {
182 | e.printStackTrace();
183 | }
184 | }
185 |
186 | /**
187 | * 删除日志文件
188 | */
189 | public static void delFile() {
190 |
191 | File file = new File(PATH, LOG_FILE_NAME);
192 | if (file.exists()) {
193 | file.delete();
194 | }
195 | }
196 |
197 | /**
198 | * 判断文件夹是否存在,如果不存在则创建文件夹
199 | *
200 | * @param path
201 | */
202 | public static void isExist(String path) {
203 | File file = new File(path);
204 | if (!file.exists()) {
205 | file.mkdirs();
206 | }
207 |
208 | }
209 |
210 | private static boolean isExistSDCard() {
211 | if (android.os.Environment.getExternalStorageState().equals(android.os.Environment
212 | .MEDIA_MOUNTED)) {
213 | return true;
214 | } else {
215 | return false;
216 | }
217 | }
218 |
219 | public static String getNowYMDHMSTime(){
220 | SimpleDateFormat mDateFormat = new SimpleDateFormat(
221 | "yyyy-MM-dd HH");
222 | String date = mDateFormat.format(new Date());
223 | return date;
224 | }
225 |
226 | public static String generateTag(String tag){
227 | if(TAG.equals(tag)){
228 | return TAG;
229 | }
230 | return TAG+"_"+tag;
231 | }
232 |
233 | }
234 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/NetManger.java:
--------------------------------------------------------------------------------
1 | package xj.network;
2 |
3 | import android.content.Context;
4 |
5 | import java.lang.reflect.Constructor;
6 | import java.lang.reflect.InvocationTargetException;
7 | import java.util.HashMap;
8 |
9 | import xj.network.mtOkHttp.OKHttpRequest;
10 |
11 | /**
12 | * @author meitu.xujun on 2017/4/1 18:03
13 | * @version 0.1
14 | */
15 |
16 | public class NetManger {
17 |
18 | private static NetRequest instance;
19 | private static Context mContext;
20 |
21 | public static NetRequest getRequest(){
22 | return instance;
23 | }
24 |
25 | static HashMap mMap=new HashMap<>();
26 |
27 | public static void init(Context context){
28 | instance = OKHttpRequest.getInstance();
29 | mContext = context.getApplicationContext();
30 | instance.init(NetManger.mContext);
31 | }
32 |
33 | public static NetRequest getRequest(Class clz){
34 | String simpleName = clz.getSimpleName();
35 | NetRequest request = mMap.get(simpleName);
36 | if(request ==null){
37 | try {
38 | Constructor constructor = clz.getDeclaredConstructor();
39 | constructor.setAccessible(true);
40 | request = constructor.newInstance();
41 | request.init(mContext);
42 | mMap.put(simpleName,request);
43 | } catch (InstantiationException e) {
44 | e.printStackTrace();
45 | } catch (IllegalAccessException e) {
46 | e.printStackTrace();
47 | } catch (NoSuchMethodException e) {
48 | e.printStackTrace();
49 | } catch (InvocationTargetException e) {
50 | e.printStackTrace();
51 | }
52 | }
53 | instance=request;
54 | return request;
55 |
56 | }
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/NetRequest.java:
--------------------------------------------------------------------------------
1 | package xj.network;
2 |
3 | import android.content.Context;
4 |
5 | import java.util.Map;
6 |
7 | /**
8 | * @author meitu.xujun on 2017/4/1 17:59
9 | * @version 0.1
10 | */
11 |
12 | public interface NetRequest {
13 |
14 | void init(Context context);
15 |
16 | void doGet(String url, final Map paramsMap, final IResponseListener iResponseListener);
17 |
18 | void doGet(String url, final Map paramsMap, NetworkOption networkOption, final IResponseListener iResponseListener);
19 |
20 |
21 | void doPost(String url, final Map paramsMap, final IResponseListener iResponseListener);
22 |
23 | void doPost(String url, final Map paramsMap, NetworkOption networkOption,
24 | final IResponseListener iResponseListener);
25 |
26 |
27 | void cancel(Object tag);
28 |
29 |
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/NetUtils.java:
--------------------------------------------------------------------------------
1 | package xj.network;
2 |
3 | import android.net.Uri;
4 | import android.support.annotation.NonNull;
5 | import android.util.Log;
6 |
7 | import java.net.URLEncoder;
8 | import java.util.HashMap;
9 | import java.util.Map;
10 |
11 | /**
12 | * @author meitu.xujun on 2017/4/12 15:47
13 | * @version 0.1
14 | */
15 |
16 | public class NetUtils {
17 |
18 | private static final String TAG = "NetUtils";
19 |
20 |
21 | public static Map getCommonParams() {
22 |
23 | final Map pairs = new HashMap();
24 |
25 | return pairs;
26 | }
27 |
28 | @NonNull
29 | public static String checkUrl(String url) {
30 | if(!url.startsWith("http:") && !url.startsWith("https:")){
31 |
32 | }
33 | return url;
34 | }
35 |
36 | public static NetworkOption checkNetworkOption(NetworkOption networkOption, String url) {
37 | if (networkOption == null) {
38 | networkOption = new NetworkOption.Builder().setTag(url).build();
39 | }
40 | return networkOption;
41 | }
42 |
43 | public static boolean needLoginAgain(int code) {
44 | return code == 10112 || code == 10113;
45 | }
46 |
47 | public static boolean isSuccessful(int code) {
48 | return code == 0;
49 | }
50 |
51 |
52 |
53 | //Add end
54 | public static String appendUrl(String origin, Map nameValuePairs) {
55 | LogUtil.i(TAG, "original url is: " + origin);
56 | if (origin == null) {
57 | return null;
58 | }
59 | if(nameValuePairs==null){
60 | return origin;
61 | }
62 | try {
63 | boolean first = true;
64 | StringBuilder urlBuilder = new StringBuilder(origin);
65 | if (!origin.contains("?")) {
66 | urlBuilder.append("?");
67 | } else {
68 | urlBuilder.append("&");
69 | first = false;
70 | }
71 | for (Map.Entry entry : nameValuePairs.entrySet()) {
72 | if (!first) {
73 | urlBuilder.append("&");
74 | } else {
75 | first = false;
76 | }
77 | String name = entry.getKey();
78 | String value = entry.getValue();
79 | Log.i(TAG, "name: " + name + ", value: " + value);
80 | urlBuilder.append(name);
81 | urlBuilder.append("=");
82 | if (value.contains(" ")) {
83 | urlBuilder.append(Uri.encode(value, null));
84 | } else {
85 | urlBuilder.append(URLEncoder.encode(value, "UTF-8"));
86 | }
87 | }
88 | Log.i(TAG, "after append get params, new url is: " + urlBuilder.toString());
89 | return urlBuilder.toString();
90 | } catch (Exception e) {
91 | e.printStackTrace();
92 | }
93 | return origin;
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/NetworkOption.java:
--------------------------------------------------------------------------------
1 | package xj.network;
2 |
3 | import java.util.Map;
4 |
5 | /**
6 | * @author meitu.xujun on 2017/9/7
7 | * @version 0.1
8 | */
9 | public class NetworkOption {
10 |
11 | /**
12 | * 网络请求的 TAG
13 | */
14 | public String mBaseUrl;
15 | public String mTag;
16 | public Map mHeaders;
17 |
18 | public NetworkOption(String tag) {
19 | this.mTag = tag;
20 | }
21 |
22 | public static final class Builder{
23 | public String tag;
24 | public Map mHeaders;
25 | public String mBaseUrl;
26 |
27 | public Builder setTag(String tag){
28 | this.tag=tag;
29 | return this;
30 | }
31 |
32 | public Builder setHeaders(Map headers){
33 | mHeaders=headers;
34 | return this;
35 |
36 | }
37 |
38 | public Builder setBaseUrl(String baseUrl) {
39 | mBaseUrl = baseUrl;
40 | return this;
41 | }
42 |
43 | public NetworkOption build(){
44 | NetworkOption networkOption = new NetworkOption(tag);
45 | networkOption.mHeaders=mHeaders;
46 | networkOption.mBaseUrl=mBaseUrl;
47 | return networkOption;
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/Utils.java:
--------------------------------------------------------------------------------
1 | package xj.network;
2 |
3 | import android.annotation.SuppressLint;
4 | import android.app.Activity;
5 | import android.app.Application;
6 | import android.os.Bundle;
7 | import android.support.annotation.NonNull;
8 | import android.util.Log;
9 |
10 | import java.lang.ref.WeakReference;
11 | import java.util.LinkedList;
12 | import java.util.List;
13 |
14 | /**
15 | * @author meitu.xujun on 2017/9/2
16 | * @version 0.1
17 | */
18 | public final class Utils {
19 |
20 | private static final String TAG = "Utils";
21 |
22 | @SuppressLint("StaticFieldLeak")
23 | private static Application sApplication;
24 |
25 | static WeakReference sTopActivityWeakRef;
26 | static List sActivityList = new LinkedList<>();
27 |
28 | private static Application.ActivityLifecycleCallbacks mCallbacks = new Application.ActivityLifecycleCallbacks() {
29 | @Override
30 | public void onActivityCreated(Activity activity, Bundle bundle) {
31 | Log.i(TAG, "onActivityCreated: =" +activity.getLocalClassName());
32 | sActivityList.add(activity);
33 | setTopActivityWeakRef(activity);
34 | }
35 |
36 | @Override
37 | public void onActivityStarted(Activity activity) {
38 | setTopActivityWeakRef(activity);
39 | }
40 |
41 | @Override
42 | public void onActivityResumed(Activity activity) {
43 | setTopActivityWeakRef(activity);
44 | }
45 |
46 | @Override
47 | public void onActivityPaused(Activity activity) {
48 |
49 | }
50 |
51 | @Override
52 | public void onActivityStopped(Activity activity) {
53 |
54 | }
55 |
56 | @Override
57 | public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
58 |
59 | }
60 |
61 | @Override
62 | public void onActivityDestroyed(Activity activity) {
63 | Log.i(TAG, "onActivityDestroyed: =" +activity.getLocalClassName());
64 | sActivityList.remove(activity);
65 | // ToastUtils.releaseView();
66 | }
67 | };
68 |
69 | private Utils() {
70 | throw new UnsupportedOperationException("u can't instantiate me...");
71 | }
72 |
73 | /**
74 | * 初始化工具类
75 | *
76 | * @param app 应用
77 | */
78 | public static void init(@NonNull final Application app) {
79 | Utils.sApplication = app;
80 | app.registerActivityLifecycleCallbacks(mCallbacks);
81 | LogUtil.init(app);
82 | }
83 |
84 | /**
85 | * 获取Application
86 | *
87 | * @return Application
88 | */
89 | public static Application getApp() {
90 | if (sApplication != null) return sApplication;
91 | throw new NullPointerException("u should init first");
92 | }
93 |
94 | private static void setTopActivityWeakRef(Activity activity) {
95 | if (sTopActivityWeakRef == null || !activity.equals(sTopActivityWeakRef.get())) {
96 | sTopActivityWeakRef = new WeakReference<>(activity);
97 | }
98 | }
99 |
100 | public static Activity getTopActivity(){
101 | return sTopActivityWeakRef.get();
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/mtOkHttp/LoggingInterceptor.java:
--------------------------------------------------------------------------------
1 | package xj.network.mtOkHttp;
2 |
3 | import com.orhanobut.logger.Logger;
4 |
5 | import java.io.IOException;
6 |
7 | import okhttp3.Interceptor;
8 | import okhttp3.Request;
9 | import okhttp3.Response;
10 |
11 | /**
12 | * @author meitu.xujun on 2017/11/15
13 | * @version 0.1
14 | */
15 | public class LoggingInterceptor implements Interceptor {
16 |
17 | @Override public Response intercept(Chain chain) throws IOException {
18 | Request request = chain.request();
19 |
20 | long t1 = System.nanoTime();
21 | Logger.i(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));
22 |
23 | Response response = chain.proceed(request);
24 |
25 | long t2 = System.nanoTime();
26 | Logger.i(String.format("Received response for %s in %.1fms%n%s",
27 | response.request().url(), (t2 - t1) / 1e6d, response.headers()));
28 |
29 | return response;
30 | }
31 | }
32 |
33 |
34 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/mtOkHttp/OKHttpRequest.java:
--------------------------------------------------------------------------------
1 | package xj.network.mtOkHttp;
2 |
3 | import android.content.Context;
4 | import android.os.Handler;
5 |
6 | import java.io.IOException;
7 | import java.util.Map;
8 | import java.util.Set;
9 | import java.util.concurrent.TimeUnit;
10 |
11 | import okhttp3.Cache;
12 | import okhttp3.Call;
13 | import okhttp3.Callback;
14 | import okhttp3.FormBody;
15 | import okhttp3.OkHttpClient;
16 | import okhttp3.Request;
17 | import okhttp3.Response;
18 | import xj.network.HttpException;
19 | import xj.network.IResponseListener;
20 | import xj.network.NetRequest;
21 | import xj.network.NetUtils;
22 | import xj.network.NetworkOption;
23 |
24 | /**
25 | * @author meitu.xujun on 2017/11/15
26 | * @version 0.1
27 | */
28 | public class OKHttpRequest implements NetRequest {
29 |
30 | static int cacheSize = 10 * 1024 * 1024; // 10 MiB
31 |
32 | private static OkHttpClient client ;
33 | private Context mContext;
34 |
35 | public static Handler mHandler=new Handler();
36 |
37 | public static Handler getHandler(){
38 | if(mHandler==null){
39 | mHandler=new Handler();
40 | }
41 | return mHandler;
42 | }
43 |
44 | @Override
45 | public void init(Context context) {
46 | mContext = context.getApplicationContext();
47 | client=getCilent();
48 | }
49 |
50 | private volatile static OKHttpRequest instance = null;
51 |
52 | private OKHttpRequest(){
53 | }
54 |
55 | public static OKHttpRequest getInstance() {
56 | if (instance == null) {
57 | synchronized (OKHttpRequest.class) {
58 | if (instance == null) {
59 | instance = new OKHttpRequest();
60 | }
61 | }
62 | }
63 |
64 |
65 | return instance;
66 | }
67 |
68 | private OkHttpClient getCilent() {
69 | if(client==null){
70 | OkHttpClient.Builder mBuilder= new OkHttpClient.Builder().
71 | connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS)
72 | .readTimeout(30, TimeUnit.SECONDS)
73 | .addInterceptor(new LoggingInterceptor())
74 | .cache(new Cache(mContext.getExternalFilesDir("okhttp"),cacheSize));
75 | client=mBuilder.build();
76 | }
77 | return client;
78 |
79 | }
80 |
81 | @Override
82 | public void doGet(String url, Map paramsMap, final IResponseListener iResponseListener) {
83 | doGet(url,paramsMap,null,iResponseListener);
84 | }
85 |
86 | @Override
87 | public void doGet(String url, Map paramsMap, NetworkOption networkOption,
88 | final IResponseListener iResponseListener) {
89 | url= NetUtils.checkUrl(url);
90 | url=NetUtils.appendUrl(url,paramsMap);
91 | final NetworkOption option=NetUtils.checkNetworkOption(networkOption,url);
92 | Request.Builder builder = new Request.Builder().url(url).tag(option.mTag);
93 | builder=configHeaders(builder,option);
94 |
95 | Request build = builder.build();
96 |
97 | getCilent().newCall(build).enqueue(new Callback() {
98 | @Override
99 | public void onFailure(Call call, IOException e) {
100 | handleError(e, iResponseListener);
101 | }
102 |
103 | @Override
104 | public void onResponse(Call call, Response response) throws IOException {
105 | handleResult(response, iResponseListener);
106 | }
107 | });
108 | }
109 |
110 | private void handleResult(Response response, final IResponseListener iResponseListener) throws IOException {
111 | final String result = response.body().string();
112 | if(iResponseListener!=null){
113 | getHandler().post(new Runnable() {
114 | @Override
115 | public void run() {
116 | iResponseListener.onResponse(result);
117 | }
118 | });
119 |
120 | }
121 | }
122 |
123 | private void handleError(IOException e, final IResponseListener iResponseListener) {
124 | if(iResponseListener!=null){
125 | final HttpException httpException = new HttpException();
126 | httpException.e=e;
127 | getHandler().post(new Runnable() {
128 | @Override
129 | public void run() {
130 | iResponseListener.onFail(httpException);
131 | }
132 | });
133 |
134 | }
135 | }
136 |
137 | private Request.Builder configHeaders(Request.Builder builder, NetworkOption option) {
138 | Map headers = option.mHeaders;
139 | if(headers==null || headers.size()==0){
140 | return builder;
141 | }
142 | Set> entries = headers.entrySet();
143 | for(Map.Entry entry: entries){
144 | String key = entry.getKey();
145 | String value = entry.getValue();
146 | builder.addHeader(key,value);
147 | }
148 | return builder;
149 |
150 | }
151 |
152 | @Override
153 | public void doPost(String url, Map paramsMap, final IResponseListener iResponseListener) {
154 | doPost(url,paramsMap,null,iResponseListener);
155 |
156 | }
157 |
158 | private FormBody.Builder configPushParam(FormBody.Builder builder, Map paramsMap) {
159 | if(paramsMap!=null){
160 | Set> entries = paramsMap.entrySet();
161 | for(Map.Entry entry:entries ){
162 | String key = entry.getKey();
163 | String value = entry.getValue();
164 | builder.add(key,value);
165 | }
166 | }
167 | return builder;
168 | }
169 |
170 | @Override
171 | public void doPost(String url, Map paramsMap, NetworkOption networkOption,
172 | final IResponseListener iResponseListener) {
173 | url= NetUtils.checkUrl(url);
174 | final NetworkOption option=NetUtils.checkNetworkOption(networkOption,url);
175 | FormBody.Builder builder = new FormBody.Builder();
176 | builder=configPushParam(builder,paramsMap);
177 | FormBody formBody = builder.build();
178 |
179 | Request.Builder requestBuilder = new Request.Builder().url(url).post(formBody).tag(option.mTag);
180 | requestBuilder=configHeaders(requestBuilder,option);
181 | Request request = requestBuilder.build();
182 | getCilent().newCall(request).enqueue(new Callback() {
183 | @Override
184 | public void onFailure(Call call, IOException e) {
185 | handleError(e,iResponseListener);
186 | }
187 |
188 | @Override
189 | public void onResponse(Call call, Response response) throws IOException {
190 | handleResult(response,iResponseListener);
191 | }
192 | });
193 | }
194 |
195 | @Override
196 | public void cancel(Object tag) {
197 | if(client!=null){
198 | if(client != null) {
199 | for(Call call : client.dispatcher().queuedCalls()) {
200 | if(call.request().tag().equals(tag))
201 | call.cancel();
202 | }
203 | for(Call call : client.dispatcher().runningCalls()) {
204 | if(call.request().tag().equals(tag))
205 | call.cancel();
206 | }
207 | }
208 | }
209 | }
210 |
211 |
212 | }
213 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/mtOkHttp/OKHttpUtils.java:
--------------------------------------------------------------------------------
1 | package xj.network.mtOkHttp;
2 |
3 | import android.content.Context;
4 | import android.os.Handler;
5 |
6 | import java.io.IOException;
7 | import java.util.Map;
8 | import java.util.concurrent.TimeUnit;
9 |
10 | import okhttp3.Cache;
11 | import okhttp3.Call;
12 | import okhttp3.Callback;
13 | import okhttp3.FormBody;
14 | import okhttp3.OkHttpClient;
15 | import okhttp3.Request;
16 | import okhttp3.Response;
17 | import xj.network.HttpException;
18 | import xj.network.IResponseListener;
19 | import xj.network.NetUtils;
20 | import xj.network.NetworkOption;
21 |
22 | import static xj.network.mtOkHttp.OKHttpRequest.cacheSize;
23 |
24 | /**
25 | * @author meitu.xujun on 2017/11/17
26 | * @version 0.1
27 | */
28 | public class OKHttpUtils {
29 |
30 | public static Handler mHandler=new Handler();
31 |
32 | public static Handler getHandler(){
33 | if(mHandler==null){
34 | mHandler=new Handler();
35 | }
36 | return mHandler;
37 | }
38 |
39 | public static void doGet(Context context,String url, Map paramsMap, NetworkOption networkOption,
40 | final IResponseListener iResponseListener){
41 | OkHttpClient.Builder mBuilder= new OkHttpClient.Builder().
42 | connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS)
43 | .readTimeout(30, TimeUnit.SECONDS)
44 | .addInterceptor(new LoggingInterceptor())
45 | .cache(new Cache(context.getExternalFilesDir("okhttp"),cacheSize));
46 | OkHttpClient cilent = mBuilder.build();
47 |
48 | Request.Builder builder = new Request.Builder().url(url);
49 |
50 |
51 | Request build = builder.build();
52 |
53 | cilent.newCall(build).enqueue(new Callback() {
54 | @Override
55 | public void onFailure(Call call, IOException e) {
56 | handleError(e, iResponseListener);
57 | }
58 |
59 | @Override
60 | public void onResponse(Call call, Response response) throws IOException {
61 | handleResult(response, iResponseListener);
62 | }
63 | });
64 | }
65 |
66 | public static void doPost(Context context,String url, Map paramsMap, NetworkOption networkOption,
67 | final IResponseListener iResponseListener) {
68 | OkHttpClient.Builder mBuilder= new OkHttpClient.Builder().
69 | connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS)
70 | .readTimeout(30, TimeUnit.SECONDS)
71 | .addInterceptor(new LoggingInterceptor())
72 | .cache(new Cache(context.getExternalFilesDir("okhttp"),cacheSize));
73 | OkHttpClient cilent = mBuilder.build();
74 |
75 | url= NetUtils.checkUrl(url);
76 | final NetworkOption option=NetUtils.checkNetworkOption(networkOption,url);
77 | FormBody.Builder builder = new FormBody.Builder();
78 | FormBody formBody = builder.build();
79 |
80 | Request.Builder requestBuilder = new Request.Builder().url(url).post(formBody).tag(option.mTag);
81 | Request request = requestBuilder.build();
82 | cilent.newCall(request).enqueue(new Callback() {
83 | @Override
84 | public void onFailure(Call call, IOException e) {
85 | handleError(e,iResponseListener);
86 | }
87 |
88 | @Override
89 | public void onResponse(Call call, Response response) throws IOException {
90 | handleResult(response,iResponseListener);
91 | }
92 | });
93 | }
94 |
95 |
96 | private static void handleResult(Response response, final IResponseListener iResponseListener) throws IOException {
97 | final String result = response.body().string();
98 | if(iResponseListener!=null){
99 | getHandler().post(new Runnable() {
100 | @Override
101 | public void run() {
102 | iResponseListener.onResponse(result);
103 | }
104 | });
105 |
106 | }
107 | }
108 |
109 | private static void handleError(IOException e, final IResponseListener iResponseListener) {
110 | if(iResponseListener!=null){
111 | final HttpException httpException = new HttpException();
112 | httpException.e=e;
113 | getHandler().post(new Runnable() {
114 | @Override
115 | public void run() {
116 | iResponseListener.onFail(httpException);
117 | }
118 | });
119 |
120 | }
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/okhttp/HttpsUtils.java:
--------------------------------------------------------------------------------
1 | package xj.network.okhttp;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 | import java.security.KeyManagementException;
6 | import java.security.KeyStore;
7 | import java.security.KeyStoreException;
8 | import java.security.NoSuchAlgorithmException;
9 | import java.security.SecureRandom;
10 | import java.security.UnrecoverableKeyException;
11 | import java.security.cert.CertificateException;
12 | import java.security.cert.CertificateFactory;
13 | import java.security.cert.X509Certificate;
14 |
15 | import javax.net.ssl.KeyManager;
16 | import javax.net.ssl.KeyManagerFactory;
17 | import javax.net.ssl.SSLContext;
18 | import javax.net.ssl.SSLSocketFactory;
19 | import javax.net.ssl.TrustManager;
20 | import javax.net.ssl.TrustManagerFactory;
21 | import javax.net.ssl.X509TrustManager;
22 |
23 | /**
24 | * @author vision
25 | * @function support the sslsocket
26 | */
27 | public class HttpsUtils {
28 | public static SSLSocketFactory getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password) {
29 | try {
30 | TrustManager[] trustManagers = prepareTrustManager(certificates);
31 | KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
32 | SSLContext sslContext = SSLContext.getInstance("SSL");
33 |
34 | sslContext.init(keyManagers, new TrustManager[]
35 | {new MyTrustManager(chooseTrustManager(trustManagers))}, new SecureRandom());
36 | return sslContext.getSocketFactory();
37 | } catch (NoSuchAlgorithmException e) {
38 | throw new AssertionError(e);
39 | } catch (KeyManagementException e) {
40 | throw new AssertionError(e);
41 | } catch (KeyStoreException e) {
42 | throw new AssertionError(e);
43 | }
44 | }
45 |
46 | private static TrustManager[] prepareTrustManager(InputStream... certificates) {
47 | if (certificates == null || certificates.length <= 0)
48 | return null;
49 | try {
50 |
51 | CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
52 | KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
53 | keyStore.load(null);
54 | int index = 0;
55 | for (InputStream certificate : certificates) {
56 | String certificateAlias = Integer.toString(index++);
57 | keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
58 | try {
59 | if (certificate != null)
60 | certificate.close();
61 | } catch (IOException e)
62 |
63 | {
64 | }
65 | }
66 | TrustManagerFactory trustManagerFactory = null;
67 |
68 | trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
69 | trustManagerFactory.init(keyStore);
70 |
71 | TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
72 |
73 | return trustManagers;
74 | } catch (NoSuchAlgorithmException e) {
75 | e.printStackTrace();
76 | } catch (CertificateException e) {
77 | e.printStackTrace();
78 | } catch (KeyStoreException e) {
79 | e.printStackTrace();
80 | } catch (Exception e) {
81 | e.printStackTrace();
82 | }
83 | return null;
84 |
85 | }
86 |
87 | private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
88 | try {
89 | if (bksFile == null || password == null)
90 | return null;
91 |
92 | KeyStore clientKeyStore = KeyStore.getInstance("BKS");
93 | clientKeyStore.load(bksFile, password.toCharArray());
94 | KeyManagerFactory keyManagerFactory = KeyManagerFactory
95 | .getInstance(KeyManagerFactory.getDefaultAlgorithm());
96 | keyManagerFactory.init(clientKeyStore, password.toCharArray());
97 | return keyManagerFactory.getKeyManagers();
98 |
99 | } catch (KeyStoreException e) {
100 | e.printStackTrace();
101 | } catch (NoSuchAlgorithmException e) {
102 | e.printStackTrace();
103 | } catch (UnrecoverableKeyException e) {
104 | e.printStackTrace();
105 | } catch (CertificateException e) {
106 | e.printStackTrace();
107 | } catch (IOException e) {
108 | e.printStackTrace();
109 | } catch (Exception e) {
110 | e.printStackTrace();
111 | }
112 | return null;
113 | }
114 |
115 | private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {
116 | for (TrustManager trustManager : trustManagers) {
117 | if (trustManager instanceof X509TrustManager) {
118 | return (X509TrustManager) trustManager;
119 | }
120 | }
121 | return null;
122 | }
123 |
124 | private static class MyTrustManager implements X509TrustManager {
125 | private X509TrustManager defaultTrustManager;
126 | private X509TrustManager localTrustManager;
127 |
128 | public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException {
129 | TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
130 | var4.init((KeyStore) null);
131 | defaultTrustManager = chooseTrustManager(var4.getTrustManagers());
132 | this.localTrustManager = localTrustManager;
133 | }
134 |
135 | @Override
136 | public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
137 |
138 | }
139 |
140 | @Override
141 | public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
142 | try {
143 | defaultTrustManager.checkServerTrusted(chain, authType);
144 | } catch (CertificateException ce) {
145 | localTrustManager.checkServerTrusted(chain, authType);
146 | }
147 | }
148 |
149 | @Override
150 | public X509Certificate[] getAcceptedIssuers() {
151 | return new X509Certificate[0];
152 | }
153 | }
154 |
155 |
156 | public static SSLSocketFactory initSSLSocketFactory() {
157 | SSLContext sslContext = null;
158 | try {
159 | sslContext = SSLContext.getInstance("SSL");
160 | X509TrustManager[] xTrustArray = new X509TrustManager[]
161 | {initTrustManager()};
162 | sslContext.init(null,
163 | xTrustArray, new SecureRandom());
164 | } catch (Exception e) {
165 | e.printStackTrace();
166 | }
167 | return sslContext.getSocketFactory();
168 | }
169 |
170 | public static X509TrustManager initTrustManager() {
171 | X509TrustManager mTrustManager = new X509TrustManager() {
172 | @Override
173 | public X509Certificate[] getAcceptedIssuers() {
174 | return new X509Certificate[]{};
175 | }
176 |
177 | @Override
178 | public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
179 | }
180 |
181 | @Override
182 | public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
183 | }
184 | };
185 | return mTrustManager;
186 | }
187 | }
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/okhttp/JsonUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 android@19code.com
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package xj.network.okhttp;
18 |
19 | import com.google.gson.Gson;
20 |
21 | import org.json.JSONArray;
22 | import org.json.JSONException;
23 | import org.json.JSONObject;
24 | import org.json.JSONTokener;
25 |
26 | import java.lang.reflect.Array;
27 | import java.util.Collection;
28 | import java.util.Map;
29 |
30 | /**
31 | * Create by h4de5ing 2016/5/7 007
32 | * checked
33 | */
34 |
35 | // toJson 对象转json
36 | // fromJson json转对象
37 | // mapToJson Map转为JSONObject
38 | // collection2Json 集合转换为JSONArray
39 | // object2Json Object对象转换为JSONArray
40 | // string2JSONObject json字符串生成JSONObject对象
41 | public class JsonUtils {
42 | public static String toJson(Object obj) {
43 | Gson gson = new Gson();
44 | return gson.toJson(obj);
45 | }
46 |
47 | public static T fromJson(String str, Class type) {
48 | Gson gson = new Gson();
49 | return gson.fromJson(str, type);
50 | }
51 |
52 | public static JSONObject map2Json(Map, ?> data) {
53 | JSONObject object = new JSONObject();
54 |
55 | for (Map.Entry, ?> entry : data.entrySet()) {
56 | String key = (String) entry.getKey();
57 | if (key == null) {
58 | throw new NullPointerException("key == null");
59 | }
60 | try {
61 | object.put(key, wrap(entry.getValue()));
62 | } catch (JSONException e) {
63 | e.printStackTrace();
64 | }
65 | }
66 |
67 | return object;
68 | }
69 |
70 | public static JSONArray collection2Json(Collection> data) {
71 | JSONArray jsonArray = new JSONArray();
72 | if (data != null) {
73 | for (Object aData : data) {
74 | jsonArray.put(wrap(aData));
75 | }
76 | }
77 | return jsonArray;
78 | }
79 |
80 | public static JSONArray object2Json(Object data) throws JSONException {
81 | if (!data.getClass().isArray()) {
82 | throw new JSONException("Not a primitive data: " + data.getClass());
83 | }
84 | final int length = Array.getLength(data);
85 | JSONArray jsonArray = new JSONArray();
86 | for (int i = 0; i < length; ++i) {
87 | jsonArray.put(wrap(Array.get(data, i)));
88 | }
89 |
90 | return jsonArray;
91 | }
92 |
93 | private static Object wrap(Object o) {
94 | if (o == null) {
95 | return null;
96 | }
97 | if (o instanceof JSONArray || o instanceof JSONObject) {
98 | return o;
99 | }
100 | try {
101 | if (o instanceof Collection) {
102 | return collection2Json((Collection>) o);
103 | } else if (o.getClass().isArray()) {
104 | return object2Json(o);
105 | }
106 | if (o instanceof Map) {
107 | return map2Json((Map, ?>) o);
108 | }
109 |
110 | if (o instanceof Boolean || o instanceof Byte || o instanceof Character || o instanceof Double || o instanceof Float || o instanceof Integer || o instanceof Long
111 | || o instanceof Short || o instanceof String) {
112 | return o;
113 | }
114 | if (o.getClass().getPackage().getName().startsWith("java.")) {
115 | return o.toString();
116 | }
117 | } catch (Exception ignored) {
118 | }
119 | return null;
120 | }
121 |
122 | public static JSONObject string2JSONObject(String json) {
123 | JSONObject jsonObject = null;
124 | try {
125 | JSONTokener jsonParser = new JSONTokener(json);
126 | jsonObject = (JSONObject) jsonParser.nextValue();
127 | } catch (Exception e) {
128 | e.printStackTrace();
129 | }
130 | return jsonObject;
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/okhttp/client/CommonOkhttpClient.java:
--------------------------------------------------------------------------------
1 | package xj.network.okhttp.client;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | import javax.net.ssl.HostnameVerifier;
6 | import javax.net.ssl.SSLSession;
7 |
8 | import okhttp3.Call;
9 | import okhttp3.Callback;
10 | import okhttp3.OkHttpClient;
11 | import okhttp3.Request;
12 | import xj.network.okhttp.HttpsUtils;
13 | import xj.network.okhttp.listener.DisposeDataHandle;
14 | import xj.network.okhttp.response.CommonFileCallback;
15 | import xj.network.okhttp.response.CommonJsonCallback;
16 |
17 | /**
18 | * Created by gechuanguang on 2017/2/17.
19 | * 邮箱:1944633835@qq.com
20 | * @function 创建okHttpclient对象,并且配置支持https,以及发送请求
21 | */
22 | public class CommonOkhttpClient {
23 |
24 | private static final int TIME_OUT = 30;
25 | private static OkHttpClient mOkHttpClient=null;
26 |
27 | //为mOkHttpClient去配置参数 类加载的时候开始创建静态代码块,并且只执行一次
28 | static {
29 | OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
30 | okHttpClientBuilder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
31 | okHttpClientBuilder.writeTimeout(TIME_OUT, TimeUnit.SECONDS);
32 | okHttpClientBuilder.readTimeout(TIME_OUT, TimeUnit.SECONDS);
33 | okHttpClientBuilder.followRedirects(true); //设置重定向 其实默认也是true
34 |
35 | /*--添加请求头 这个看个人需求 --*/
36 | // okHttpClientBuilder.addInterceptor(new Interceptor() {
37 | // @Override
38 | // public Response intercept(Chain chain) throws IOException {
39 | // Request request = chain.request()
40 | // .newBuilder()
41 | // .addHeader("User-Agent", "Android—Mobile") // 标明发送本次请求的客户端
42 | // .build();
43 | // return chain.proceed(request);
44 | // }
45 | // });
46 |
47 | //添加https支持
48 | okHttpClientBuilder.hostnameVerifier(new HostnameVerifier() {
49 | @Override
50 | public boolean verify(String s, SSLSession sslSession) {
51 | return true;
52 | }
53 | });
54 | /**
55 | * trust all the https point
56 | */
57 | okHttpClientBuilder.sslSocketFactory(HttpsUtils.initSSLSocketFactory(),HttpsUtils.initTrustManager());
58 | mOkHttpClient = okHttpClientBuilder.build();
59 | }
60 |
61 | /**
62 | * 发送具体的http/https的请求
63 | * @param request
64 | * @param commonCallback
65 | * @return Call
66 | */
67 | public static Call sendRequest(Request request, CommonJsonCallback commonCallback){
68 | Call call=mOkHttpClient.newCall(request);
69 | call.enqueue(commonCallback);
70 | return call;
71 | }
72 |
73 | /**
74 | * 发送具体的http/https的请求
75 | * @param request
76 | * @param commonCallback
77 | * @return Call
78 | */
79 | public static Call sendRequest(Request request, Callback commonCallback){
80 | Call call=mOkHttpClient.newCall(request);
81 | call.enqueue(commonCallback);
82 | return call;
83 | }
84 |
85 |
86 | /**
87 | * 文件下载
88 | * @param request
89 | * @param handle
90 | * @return
91 | */
92 | public static Call downloadFile(Request request, DisposeDataHandle handle) {
93 | Call call = mOkHttpClient.newCall(request);
94 | call.enqueue(new CommonFileCallback(handle));
95 | return call;
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/okhttp/exception/OkHttpException.java:
--------------------------------------------------------------------------------
1 | package xj.network.okhttp.exception;
2 |
3 | /**********************************************************
4 | * @文件名称:LogicException.java
5 | * @文件作者:renzhiqiang
6 | * @创建时间:2015年8月19日 上午10:05:08
7 | * @文件描述:自定义异常类,返回ecode,emsg到业务层
8 | * @修改历史:2015年8月19日创建初始版本
9 | **********************************************************/
10 | public class OkHttpException extends Exception {
11 | private static final long serialVersionUID = 1L;
12 |
13 | /**
14 | * the server return code
15 | */
16 | private int ecode;
17 |
18 | /**
19 | * the server return error message
20 | */
21 | private Object emsg;
22 |
23 | public OkHttpException(int ecode, Object emsg) {
24 | this.ecode = ecode;
25 | this.emsg = emsg;
26 | }
27 |
28 | public int getEcode() {
29 | return ecode;
30 | }
31 |
32 | public Object getEmsg() {
33 | return emsg;
34 | }
35 | }
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/okhttp/listener/DisposeDataHandle.java:
--------------------------------------------------------------------------------
1 | package xj.network.okhttp.listener;
2 |
3 |
4 | /**
5 | * @author vision
6 | *
7 | */
8 | public class DisposeDataHandle
9 | {
10 | public DisposeDataListener mListener = null;
11 | public Class> mClass = null;
12 | public String mSource = null;
13 |
14 | public DisposeDataHandle(DisposeDataListener listener)
15 | {
16 | this.mListener = listener;
17 | }
18 |
19 | public DisposeDataHandle(DisposeDataListener listener, Class> clazz)
20 | {
21 | this.mListener = listener;
22 | this.mClass = clazz;
23 | }
24 |
25 | public DisposeDataHandle(DisposeDataListener listener, String source)
26 | {
27 | this.mListener = listener;
28 | this.mSource = source;
29 | }
30 | }
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/okhttp/listener/DisposeDataListener.java:
--------------------------------------------------------------------------------
1 | package xj.network.okhttp.listener;
2 |
3 | import xj.network.okhttp.exception.OkHttpException;
4 |
5 | /**********************************************************
6 | * @文件名称:DisposeDataListener.java
7 | * @文件作者:renzhiqiang
8 | * @创建时间:2015年8月19日 上午11:01:13
9 | * @文件描述:业务逻辑层真正处理的地方,包括java层异常和业务层异常
10 | * @修改历史:2015年8月19日创建初始版本
11 | **********************************************************/
12 | public interface DisposeDataListener {
13 |
14 | /**
15 | * 请求成功回调事件处理
16 | */
17 | public void onSuccess(T t);
18 |
19 | /**
20 | * 请求失败回调事件处理
21 | */
22 | public void onFailure(OkHttpException e);
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/okhttp/listener/DisposeDownloadListener.java:
--------------------------------------------------------------------------------
1 | package xj.network.okhttp.listener;
2 |
3 | /**
4 | * @author vision
5 | * @function 监听下载进度
6 | */
7 | public interface DisposeDownloadListener extends DisposeDataListener {
8 | public void onProgress(int progrss);
9 | }
10 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/okhttp/listener/DisposeHandleCookieListener.java:
--------------------------------------------------------------------------------
1 | package xj.network.okhttp.listener;
2 |
3 | import java.util.ArrayList;
4 |
5 | /**********************************************************
6 | * @文件名称:DisposeHandleCookieListener.java
7 | * @文件作者:renzhiqiang
8 | * @创建时间:2016年1月26日 下午10:17:53
9 | * @文件描述:当需要专门处理Cookie时创建此回调接口
10 | * @修改历史:2016年1月26日创建初始版本
11 | **********************************************************/
12 | public interface DisposeHandleCookieListener extends DisposeDataListener
13 | {
14 | public void onCookie(ArrayList cookieStrLists);
15 | }
16 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/okhttp/request/CommonRequest.java:
--------------------------------------------------------------------------------
1 | package xj.network.okhttp.request;
2 |
3 | import java.io.File;
4 | import java.util.Map;
5 |
6 | import okhttp3.FormBody;
7 | import okhttp3.Headers;
8 | import okhttp3.MediaType;
9 | import okhttp3.MultipartBody;
10 | import okhttp3.Request;
11 | import okhttp3.RequestBody;
12 |
13 | /**
14 | * Created by gechuanguang on 2017/2/17.
15 | * 邮箱:1944633835@qq.com
16 | * @function 接收请求参数,为我们生成Request对象
17 | */
18 | public class CommonRequest {
19 | /**
20 | * @param url
21 | * @param params
22 | * @return 返回一个创建好post的Request对象
23 | */
24 | public static Request createPostRequest(String url, RequestParams params){
25 |
26 | FormBody.Builder mFormBodybuilder = new FormBody.Builder();
27 | if(params!=null){
28 | for(Map.Entry entry: params.urlParams.entrySet()){
29 | // 将请求参数逐一添加到请求体中
30 | mFormBodybuilder.add(entry.getKey(),entry.getValue());
31 | }
32 | }
33 | FormBody mFormBody=mFormBodybuilder.build();
34 | return new Request.Builder()
35 | .url(url)
36 | .post(mFormBody)
37 | .build();
38 | }
39 |
40 | /**
41 | * @param url
42 | * @param params
43 | * @return 返回一个创建好get的Request对象
44 | */
45 | public static Request createGetRequest(String url, RequestParams params){
46 |
47 | StringBuilder urlBuilder=new StringBuilder(url).append("?");
48 | if(params!=null){
49 | for(Map.Entry entry: params.urlParams.entrySet()){
50 | // 将请求参数逐一添加到请求体中
51 | urlBuilder.append(entry.getKey()).append("=")
52 | .append(entry.getValue())
53 | .append("&");
54 | }
55 | }
56 | return new Request.Builder()
57 | .url(urlBuilder.substring(0,urlBuilder.length()-1)) //要把最后的&符号去掉
58 | .get()
59 | .build();
60 | }
61 |
62 | /**
63 | * 文件上传请求
64 | *
65 | * @return
66 | */
67 | private static final MediaType FILE_TYPE = MediaType.parse("application/octet-stream");
68 |
69 | public static Request createMultiPostRequest(String url, RequestParams params) {
70 |
71 | MultipartBody.Builder requestBody = new MultipartBody.Builder();
72 | requestBody.setType(MultipartBody.FORM);
73 | if (params != null) {
74 | for (Map.Entry entry : params.fileParams.entrySet()) {
75 | if (entry.getValue() instanceof File) {
76 | requestBody.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""),
77 | RequestBody.create(FILE_TYPE, (File) entry.getValue()));
78 | } else if (entry.getValue() instanceof String) {
79 |
80 | requestBody.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""),
81 | RequestBody.create(null, (String) entry.getValue()));
82 | }
83 | }
84 | }
85 | return new Request.Builder()
86 | .url(url)
87 | .post(requestBody.build())
88 | .build();
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/okhttp/request/RequestParams.java:
--------------------------------------------------------------------------------
1 | package xj.network.okhttp.request;
2 |
3 | import java.io.FileNotFoundException;
4 | import java.util.HashMap;
5 | import java.util.Map;
6 | import java.util.concurrent.ConcurrentHashMap;
7 |
8 | /**
9 | * @author vision
10 | */
11 | public class RequestParams {
12 |
13 | public ConcurrentHashMap urlParams = new ConcurrentHashMap();
14 | public ConcurrentHashMap fileParams = new ConcurrentHashMap();
15 |
16 | /**
17 | * Constructs a new empty {@code RequestParams} instance.
18 | */
19 | public RequestParams() {
20 | this((Map) null);
21 | }
22 |
23 | /**
24 | * Constructs a new RequestParams instance containing the key/value string
25 | * params from the specified map.
26 | *
27 | * @param source the source key/value string map to add.
28 | */
29 | public RequestParams(Map source) {
30 | if (source != null) {
31 | for (Map.Entry entry : source.entrySet()) {
32 | put(entry.getKey(), entry.getValue());
33 | }
34 | }
35 | }
36 |
37 | /**
38 | * Constructs a new RequestParams instance and populate it with a single
39 | * initial key/value string param.
40 | *
41 | * @param key the key name for the intial param.
42 | * @param value the value string for the initial param.
43 | */
44 | public RequestParams(final String key, final String value) {
45 | this(new HashMap() {
46 | {
47 | put(key, value);
48 | }
49 | });
50 | }
51 |
52 | /**
53 | * Adds a key/value string pair to the request.
54 | *
55 | * @param key the key name for the new param.
56 | * @param value the value string for the new param.
57 | */
58 | public void put(String key, String value) {
59 | if (key != null && value != null) {
60 | urlParams.put(key, value);
61 | }
62 | }
63 |
64 | public void put(String key, Object object) throws FileNotFoundException {
65 |
66 | if (key != null) {
67 | fileParams.put(key, object);
68 | }
69 | }
70 |
71 | public boolean hasParams() {
72 | if(urlParams.size() > 0 || fileParams.size() > 0){
73 |
74 | return true;
75 | }
76 | return false;
77 | }
78 | }
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/okhttp/response/CommonFileCallback.java:
--------------------------------------------------------------------------------
1 | package xj.network.okhttp.response;//package me.gcg.network.okhttp.response;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 | import android.os.Message;
6 |
7 | import java.io.File;
8 | import java.io.FileOutputStream;
9 | import java.io.IOException;
10 | import java.io.InputStream;
11 |
12 | import okhttp3.Call;
13 | import okhttp3.Callback;
14 | import okhttp3.Response;
15 | import xj.network.okhttp.exception.OkHttpException;
16 | import xj.network.okhttp.listener.DisposeDataHandle;
17 | import xj.network.okhttp.listener.DisposeDownloadListener;
18 |
19 | /**
20 | * *******************************************************
21 | *
22 | * @文件名称:CommonFileCallback.java
23 | * @文件作者:renzhiqiang
24 | * @创建时间:2016年1月23日 下午5:32:01
25 | * @文件描述:专门处理文件下载回调
26 | * @修改历史:2016年1月23日创建初始版本 ********************************************************
27 | */
28 | public class CommonFileCallback implements Callback {
29 | /**
30 | * the java layer exception, do not same to the logic error
31 | */
32 | protected final int NETWORK_ERROR = -1; // the network relative error
33 | protected final int IO_ERROR = -2; // the JSON relative error
34 | protected final String EMPTY_MSG = "";
35 | /**
36 | * 将其它线程的数据转发到UI线程
37 | */
38 | private static final int PROGRESS_MESSAGE = 0x01;
39 | private Handler mDeliveryHandler;
40 | private DisposeDownloadListener mListener;
41 | private String mFilePath;
42 | private int mProgress;
43 |
44 | public CommonFileCallback(DisposeDataHandle handle) {
45 | this.mListener = (DisposeDownloadListener) handle.mListener;
46 | this.mFilePath = handle.mSource;
47 | this.mDeliveryHandler = new Handler(Looper.getMainLooper()) {
48 | @Override
49 | public void handleMessage(Message msg) {
50 | switch (msg.what) {
51 | case PROGRESS_MESSAGE:
52 | mListener.onProgress((int) msg.obj);
53 | break;
54 | }
55 | }
56 | };
57 | }
58 |
59 | @Override
60 | public void onFailure(final Call call, final IOException ioexception) {
61 | mDeliveryHandler.post(new Runnable() {
62 | @Override
63 | public void run() {
64 | mListener.onFailure(new OkHttpException(NETWORK_ERROR, ioexception));
65 | }
66 | });
67 | }
68 |
69 | @Override
70 | public void onResponse(Call call, Response response) throws IOException {
71 | final File file = handleResponse(response);
72 | mDeliveryHandler.post(new Runnable() {
73 | @Override
74 | public void run() {
75 | if (file != null) {
76 | mListener.onSuccess(file);
77 | } else {
78 | mListener.onFailure(new OkHttpException(IO_ERROR, EMPTY_MSG));
79 | }
80 | }
81 | });
82 | }
83 |
84 | /**
85 | * 此时还在子线程中,不则调用回调接口
86 | *
87 | * @param response
88 | * @return
89 | */
90 | private File handleResponse(Response response) {
91 | if (response == null) {
92 | return null;
93 | }
94 |
95 | InputStream inputStream = null;
96 | File file = null;
97 | FileOutputStream fos = null;
98 | byte[] buffer = new byte[2048];
99 | int length;
100 | int currentLength = 0;
101 | double sumLength;
102 | try {
103 | checkLocalFilePath(mFilePath);
104 | file = new File(mFilePath);
105 | fos = new FileOutputStream(file);
106 | inputStream = response.body().byteStream();
107 | sumLength = (double) response.body().contentLength();
108 |
109 | while ((length = inputStream.read(buffer)) != -1) {
110 | fos.write(buffer, 0, length);
111 | currentLength += length;
112 | mProgress = (int) (currentLength / sumLength * 100);
113 | mDeliveryHandler.obtainMessage(PROGRESS_MESSAGE, mProgress).sendToTarget();
114 | }
115 | fos.flush();
116 | } catch (Exception e) {
117 | file = null;
118 | } finally {
119 | try {
120 | if (fos != null) {
121 | fos.close();
122 | }
123 | if (inputStream != null) {
124 |
125 | inputStream.close();
126 | }
127 | } catch (IOException e) {
128 | e.printStackTrace();
129 | }
130 | }
131 | return file;
132 | }
133 |
134 | private void checkLocalFilePath(String localFilePath) {
135 | File path = new File(localFilePath.substring(0,
136 | localFilePath.lastIndexOf("/") + 1));
137 | File file = new File(localFilePath);
138 | if (!path.exists()) {
139 | path.mkdirs();
140 | }
141 | if (!file.exists()) {
142 | try {
143 | file.createNewFile();
144 | } catch (IOException e) {
145 | e.printStackTrace();
146 | }
147 | }
148 | }
149 | }
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/okhttp/response/CommonJsonCallback.java:
--------------------------------------------------------------------------------
1 | package xj.network.okhttp.response;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 |
6 | import java.io.IOException;
7 | import java.util.ArrayList;
8 |
9 | import okhttp3.Call;
10 | import okhttp3.Callback;
11 | import okhttp3.Headers;
12 | import okhttp3.Response;
13 | import xj.network.okhttp.JsonUtils;
14 | import xj.network.okhttp.exception.OkHttpException;
15 | import xj.network.okhttp.listener.DisposeDataHandle;
16 | import xj.network.okhttp.listener.DisposeDataListener;
17 | import xj.network.okhttp.listener.DisposeHandleCookieListener;
18 |
19 | /**
20 | * @author vision
21 | * @function 专门处理JSON的回调
22 | */
23 | public class CommonJsonCallback implements Callback {
24 |
25 | /**
26 | * the logic layer exception, may alter in different app
27 | */
28 | protected final String RESULT_CODE = "ecode"; // 有返回则对于http请求来说是成功的,但还有可能是业务逻辑上的错误
29 | protected final int RESULT_CODE_VALUE = 0;
30 | protected final String ERROR_MSG = "emsg";
31 | protected final String EMPTY_MSG = "";
32 | protected final String COOKIE_STORE = "Set-Cookie"; // decide the server it
33 | // can has the value of
34 | // set-cookie2
35 |
36 | /**
37 | * the java layer exception, do not same to the logic error
38 | */
39 | protected final int NETWORK_ERROR = -1; // the network relative error
40 | protected final int JSON_ERROR = -2; // the JSON relative error
41 | protected final int OTHER_ERROR = -3; // the unknow error
42 |
43 | /**
44 | * 将其它线程的数据转发到UI线程
45 | */
46 | private Handler mDeliveryHandler;
47 | private DisposeDataListener mListener;
48 | private Class> mClass;
49 |
50 | public CommonJsonCallback(DisposeDataHandle handle) {
51 | this.mListener = handle.mListener;
52 | this.mClass = handle.mClass;
53 | this.mDeliveryHandler = new Handler(Looper.getMainLooper());
54 | }
55 |
56 | @Override
57 | public void onFailure(final Call call, final IOException ioexception) {
58 | /**
59 | * 此时还在非UI线程,因此要转发
60 | */
61 | mDeliveryHandler.post(new Runnable() {
62 | @Override
63 | public void run() {
64 | mListener.onFailure(new OkHttpException(NETWORK_ERROR, ioexception));
65 | }
66 | });
67 |
68 | }
69 | @Override
70 | public void onResponse(final Call call, final Response response) throws IOException {
71 | final String result = response.body().string();
72 | final ArrayList cookieLists = handleCookie(response.headers());
73 | mDeliveryHandler.post(new Runnable() {
74 | @Override
75 | public void run() {
76 | handleResponse(result);
77 | /**
78 | * handle the cookie
79 | */
80 | if (mListener instanceof DisposeHandleCookieListener) {
81 | ((DisposeHandleCookieListener) mListener).onCookie(cookieLists);
82 | }
83 | }
84 | });
85 | }
86 | private ArrayList handleCookie(Headers headers) {
87 | ArrayList tempList = new ArrayList();
88 | for (int i = 0; i < headers.size(); i++) {
89 | if (headers.name(i).equalsIgnoreCase(COOKIE_STORE)) {
90 | tempList.add(headers.value(i));
91 | }
92 | }
93 | return tempList;
94 | }
95 | private void handleResponse(Object responseObj) {
96 | if (responseObj == null || responseObj.toString().trim().equals("")) {
97 | mListener.onFailure(new OkHttpException(NETWORK_ERROR, EMPTY_MSG));
98 | return;
99 | }
100 | try {
101 | /**
102 | * 协议确定后看这里如何修改
103 | */
104 | // JSONObject result = new JSONObject(responseObj.toString());
105 | String result=responseObj.toString();
106 | if (mClass == null) {
107 |
108 | //发送JSONObject类型
109 | // mListener.onSuccess(result);
110 | // 发送json字符串
111 | mListener.onSuccess(result);
112 |
113 | } else {
114 | /*--将json转化成实体类--*/
115 | Object obj = JsonUtils.fromJson(result.toString(), mClass);
116 | if (obj != null) {
117 | mListener.onSuccess(obj);
118 | } else {
119 | mListener.onFailure(new OkHttpException(JSON_ERROR, EMPTY_MSG));
120 | }
121 | }
122 | } catch (Exception e) {
123 | mListener.onFailure(new OkHttpException(OTHER_ERROR, e.getMessage()));
124 | e.printStackTrace();
125 | }
126 | }
127 | }
--------------------------------------------------------------------------------
/library/src/main/java/xj/network/volley/VolleyRequest.java:
--------------------------------------------------------------------------------
1 | package xj.network.volley;
2 |
3 | import android.content.Context;
4 | import android.support.annotation.NonNull;
5 |
6 | import com.android.volley.AuthFailureError;
7 | import com.android.volley.DefaultRetryPolicy;
8 | import com.android.volley.Request;
9 | import com.android.volley.RequestQueue;
10 | import com.android.volley.Response;
11 | import com.android.volley.VolleyError;
12 | import com.android.volley.toolbox.StringRequest;
13 | import com.android.volley.toolbox.Volley;
14 |
15 | import java.util.HashMap;
16 | import java.util.Iterator;
17 | import java.util.Map;
18 | import java.util.Set;
19 |
20 | import xj.network.HttpException;
21 | import xj.network.IResponseListener;
22 | import xj.network.LogUtil;
23 | import xj.network.NetRequest;
24 | import xj.network.NetUtils;
25 | import xj.network.NetworkOption;
26 |
27 | /**
28 | * @author meitu.xujun on 2017/9/6
29 | * @version 0.1
30 | */
31 |
32 | public class VolleyRequest implements NetRequest {
33 |
34 | private static final String TAG = "VolleyRequest";
35 |
36 | private volatile static VolleyRequest instance = null;
37 | private static RequestQueue requestQueue;
38 | private Context mContext;
39 |
40 | private VolleyRequest() {
41 | }
42 |
43 | public static VolleyRequest getInstance() {
44 | synchronized (VolleyRequest.class) {
45 | if (instance == null) {
46 | instance = new VolleyRequest();
47 | }
48 | }
49 |
50 | return instance;
51 | }
52 |
53 |
54 |
55 |
56 |
57 | @Override
58 | public void init(Context context) {
59 | mContext = context.getApplicationContext();
60 | requestQueue=getQueue();
61 |
62 | }
63 |
64 | @Override
65 | public void doGet(String url, Map paramsMap, IResponseListener iResponseListener) {
66 | doGet(url, paramsMap, null, iResponseListener);
67 | }
68 |
69 | @Override
70 | public void doGet(String url, final Map paramsMap, NetworkOption
71 | networkOption, final IResponseListener iResponseListener) {
72 | RequestQueue queue = getQueue();
73 | url = NetUtils.checkUrl(url);
74 | url = NetUtils.appendUrl(url, paramsMap);
75 |
76 | printMes(url, paramsMap);
77 | // 检查 NetworkOption 的合法性
78 | final NetworkOption option = NetUtils.checkNetworkOption(networkOption, url);
79 | StringRequest request = new StringRequest(Request.Method.GET, url, new Response
80 | .Listener() {
81 | @Override
82 | public void onResponse(String response) {
83 | handleResult(response, iResponseListener);
84 | }
85 | }, new Response.ErrorListener() {
86 | @Override
87 | public void onErrorResponse(VolleyError error) {
88 | handleError(error, iResponseListener);
89 | }
90 | }) {
91 |
92 | @Override
93 | public Map getHeaders() throws AuthFailureError {
94 | return handleHeaderMap(option);
95 | }
96 |
97 | };
98 | // 给每一个请求设置Tag,默认是URl
99 | request.setTag(option.mTag);
100 | request.setRetryPolicy(new DefaultRetryPolicy(15 * 1000, 1, 1.0f));
101 | queue.add(request);
102 |
103 | }
104 |
105 | @NonNull
106 | private Map handleHeaderMap(NetworkOption option) {
107 | Map headers = option.mHeaders;
108 | // 如果配置的 headers 不为空,采用配置的,否则采用默认的 headers
109 | if (headers != null && headers.size() > 0) {
110 | return headers;
111 | }
112 |
113 | return new HashMap();
114 | }
115 |
116 | private void printMes(String url, Map paramsMap) {
117 | LogUtil.i(" url=" + url);
118 |
119 | }
120 |
121 | @Override
122 | public void doPost(String url, Map paramsMap, IResponseListener
123 | iResponseListener) {
124 | doPost(url, paramsMap, null, iResponseListener);
125 | }
126 |
127 | @Override
128 | public void doPost(String url, final Map paramsMap, NetworkOption
129 | networkOption, final IResponseListener iResponseListener) {
130 | url = NetUtils.checkUrl(url);
131 | final NetworkOption option = NetUtils.checkNetworkOption(networkOption, url);
132 | printMes(url, paramsMap);
133 | // This is Get
134 | // url = MeiosUtils.appendUrl(url, paramsMap);
135 | StringRequest request = new StringRequest(Request.Method.POST, url, new Response
136 | .Listener() {
137 | @Override
138 | public void onResponse(String response) {
139 | handleResult(response, iResponseListener);
140 | }
141 | }, new Response.ErrorListener() {
142 | @Override
143 | public void onErrorResponse(VolleyError error) {
144 | handleError(error, iResponseListener);
145 |
146 | }
147 | }) {
148 |
149 | @Override
150 | public Map getHeaders() throws AuthFailureError {
151 | return handleHeaderMap(option);
152 | }
153 |
154 | @Override
155 | protected Map getParams() throws AuthFailureError {
156 | return paramsMap;
157 | }
158 | };
159 | RequestQueue queue = getQueue();
160 | // 给每一个请求设置Tag,默认是URl
161 | request.setTag(option.mTag);
162 | request.setRetryPolicy(new DefaultRetryPolicy(15 * 1000, 1, 1.0f));
163 | queue.add(request);
164 | }
165 |
166 | private void handleResult(String response, IResponseListener iResponseListener) {
167 | if(iResponseListener!=null){
168 | iResponseListener.onResponse(response);
169 | }
170 |
171 | }
172 |
173 | // 处理重新登录的相关逻辑
174 | private void handleLoginAgain() {
175 |
176 | }
177 |
178 | private void handleError(VolleyError error, IResponseListener iResponseListener) {
179 | HttpException httpException = new HttpException();
180 | httpException.e=error;
181 | if(iResponseListener!=null){
182 | iResponseListener.onFail(httpException);
183 | }
184 |
185 | }
186 |
187 | @Override
188 | public void cancel(final Object tag) {
189 |
190 | getQueue().cancelAll(new RequestQueue.RequestFilter() {
191 | @Override
192 | public boolean apply(Request> request) {
193 | return request.getTag().toString().equals(tag.toString());
194 |
195 | }
196 | });
197 | }
198 |
199 | private RequestQueue getQueue() {
200 | if(requestQueue==null){
201 | requestQueue=Volley.newRequestQueue(mContext);
202 | }
203 |
204 | return requestQueue;
205 | }
206 |
207 | public static String getString(Map map) {
208 | Set> entrySet = map.entrySet();
209 | Iterator> iterator = entrySet.iterator();
210 | StringBuilder sb = new StringBuilder();
211 | while (iterator.hasNext()) {
212 | Map.Entry entry = iterator.next();
213 | String key = entry.getKey();
214 | String value = entry.getValue();
215 | sb.append(key).append(" ").append(value).append("\n");
216 | }
217 | return sb.toString();
218 |
219 | }
220 | }
221 |
--------------------------------------------------------------------------------
/library/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Library
3 |
4 |
--------------------------------------------------------------------------------
/library/src/test/java/xj/network/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package xj.network;
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() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':library'
2 |
--------------------------------------------------------------------------------