├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── styles.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
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── layout
│ │ │ │ └── activity_main.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── xwdz
│ │ │ └── httpsimple
│ │ │ ├── APISignatureIntercept.java
│ │ │ ├── AppendGlobalParamsIntercept.java
│ │ │ ├── App.java
│ │ │ └── MainActivity.java
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── xwdz
│ │ │ └── httpsimple
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── xwdz
│ │ └── httpsimple
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── mylibrary
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ └── values
│ │ │ │ └── strings.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── xwdz
│ │ │ └── http
│ │ │ ├── callback
│ │ │ ├── InterceptRequest.java
│ │ │ ├── IBaseEasyCallback.java
│ │ │ ├── StringEasyCallbackImpl.java
│ │ │ ├── BaseEasyCallbackImpl.java
│ │ │ └── FileEasyCallbackImpl.java
│ │ │ ├── core
│ │ │ ├── EasyCall.java
│ │ │ ├── EasyRequestManager.java
│ │ │ ├── HttpUrlConnection.java
│ │ │ └── Request.java
│ │ │ ├── error
│ │ │ └── EasyHTTPException.java
│ │ │ ├── thread
│ │ │ ├── EasyThreadPools.java
│ │ │ └── RequestTaskProxy.java
│ │ │ ├── EasyNetwork.java
│ │ │ ├── EasyNetworkConfig.java
│ │ │ └── Util.java
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── xwdz
│ │ │ └── http
│ │ │ └── ExampleUnitTest.java
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── xwdz
│ │ └── http
│ │ └── ExampleInstrumentedTest.java
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── jpg
└── logo.jpg
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .idea
├── encodings.xml
├── vcs.xml
├── misc.xml
├── runConfigurations.xml
├── gradle.xml
└── inspectionProfiles
│ └── Project_Default.xml
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── README.md
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/mylibrary/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':mylibrary'
2 |
--------------------------------------------------------------------------------
/jpg/logo.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xwdz/EasyNetwork/HEAD/jpg/logo.jpg
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xwdz/EasyNetwork/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | httpSimple
3 |
4 |
--------------------------------------------------------------------------------
/mylibrary/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | My Library
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xwdz/EasyNetwork/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xwdz/EasyNetwork/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xwdz/EasyNetwork/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xwdz/EasyNetwork/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xwdz/EasyNetwork/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/mylibrary/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xwdz/EasyNetwork/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xwdz/EasyNetwork/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xwdz/EasyNetwork/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xwdz/EasyNetwork/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xwdz/EasyNetwork/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu May 09 17:28:38 CST 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip
7 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/xwdz/http/callback/InterceptRequest.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http.callback;
2 |
3 | import com.xwdz.http.core.Request;
4 |
5 | /**
6 | * @author xingwei.huang (xwdz9989@gmail.com)
7 | * @since v1.0.0
8 | */
9 | public interface InterceptRequest {
10 |
11 | Request onInterceptRequest(Request request);
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/mylibrary/src/test/java/com/xwdz/http/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/xwdz/httpsimple/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.httpsimple;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/xwdz/http/callback/IBaseEasyCallback.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http.callback;
2 |
3 | import com.xwdz.http.core.EasyCall;
4 |
5 | import java.net.HttpURLConnection;
6 |
7 | /**
8 | * @author xingwei.huang (xwdz9989@gmail.com)
9 | * @since v1.0.0
10 | */
11 | public interface IBaseEasyCallback {
12 |
13 | void onResponse(EasyCall call, HttpURLConnection httpURLConnection);
14 |
15 | void onFailure(EasyCall call, Throwable error);
16 |
17 | void onCancel();
18 | }
19 |
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/xwdz/http/core/EasyCall.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http.core;
2 |
3 | /**
4 | * @author xingwei.huang (xwdz9989@gmail.com)
5 | * @since v1.0.0
6 | */
7 | public class EasyCall {
8 |
9 | private Request request;
10 |
11 | public EasyCall() {
12 | }
13 |
14 | public EasyCall(Request request) {
15 | this.request = request;
16 | }
17 |
18 | public Request getRequest() {
19 | return request;
20 | }
21 |
22 | public void setRequest(Request request) {
23 | this.request = request;
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 |
15 |
16 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/mylibrary/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/mylibrary/src/androidTest/java/com/xwdz/http/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumented test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.xwdz.http.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/xwdz/httpsimple/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.httpsimple;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumented test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.xwdz.httpsimple", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/xwdz/http/error/EasyHTTPException.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http.error;
2 |
3 | import java.io.Serializable;
4 |
5 | /**
6 | * @author xingwei.huang (xwdz9989@gmail.com)
7 | * @since v1.0.0
8 | */
9 | public class EasyHTTPException extends Throwable implements Serializable {
10 |
11 | private static final long serialVersionUID = -492948457991527824L;
12 |
13 | public static final class Error {
14 | public static final String CANCEL_REQUEST = "1004";
15 | }
16 |
17 |
18 | public final String message;
19 | public final String code;
20 |
21 |
22 | public EasyHTTPException(String message, String code) {
23 | this.message = message;
24 | this.code = code;
25 | }
26 |
27 | @Override
28 | public String toString() {
29 | return "EasyHTTPException{" +
30 | "message='" + message + '\'' +
31 | ", code='" + code + '\'' +
32 | '}';
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xwdz/httpsimple/APISignatureIntercept.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.httpsimple;
2 |
3 | import android.util.Log;
4 |
5 | import com.xwdz.http.callback.InterceptRequest;
6 | import com.xwdz.http.core.Request;
7 |
8 | import java.util.HashMap;
9 |
10 | /**
11 | * @author xingwei.huang (xwdz9989@gmail.com)
12 | * @since v1.0.0
13 | */
14 | public class APISignatureIntercept implements InterceptRequest {
15 | @Override
16 | public Request onInterceptRequest(Request request) {
17 |
18 | HashMap params = new HashMap<>();
19 | HashMap headers = new HashMap<>();
20 |
21 | // todo 统一加密 param or header or url
22 | Request realRequest = new Request.Builder()
23 | .url(request.url)
24 | .tag(request.tag)
25 | .addHeaders(headers)
26 | .addParams(params)
27 | .build();
28 |
29 | Log.w("EasyHttp", "signature intercept:" + realRequest.toString());
30 | return realRequest;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/xwdz/http/core/EasyRequestManager.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http.core;
2 |
3 | import com.xwdz.http.EasyNetworkConfig;
4 | import com.xwdz.http.callback.IBaseEasyCallback;
5 | import com.xwdz.http.thread.RequestTaskProxy;
6 |
7 | import java.util.HashMap;
8 | import java.util.Map;
9 |
10 | /**
11 | * @author xingwei.huang (xwdz9989@gmail.com)
12 | * @since v1.0.0
13 | */
14 | public class EasyRequestManager {
15 |
16 | private HashMap mRequestHashMap;
17 |
18 | public EasyRequestManager() {
19 | mRequestHashMap = new HashMap<>();
20 | }
21 |
22 | public void performRequest(EasyNetworkConfig config, Request request, IBaseEasyCallback baseEasyCallback) {
23 | final RequestTaskProxy task = new RequestTaskProxy(config, request, baseEasyCallback);
24 | task.start();
25 | mRequestHashMap.put(task.getRequest().tag.toString(), task);
26 |
27 | }
28 |
29 |
30 | public void performCancelRequest(Object tag) {
31 | RequestTaskProxy requestWrapper = mRequestHashMap.get(tag.toString());
32 | if (requestWrapper != null) {
33 | requestWrapper.cancel();
34 | }
35 | }
36 |
37 | public void performCancelAll() {
38 | for (Map.Entry entry : mRequestHashMap.entrySet()) {
39 | entry.getValue().cancel();
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xwdz/httpsimple/AppendGlobalParamsIntercept.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.httpsimple;
2 |
3 | import com.xwdz.http.callback.InterceptRequest;
4 | import com.xwdz.http.core.Request;
5 |
6 | import java.util.HashMap;
7 | import java.util.Map;
8 |
9 | /**
10 | * 添加所有请求公共参数
11 | * @author xingwei.huang (xwdz9989@gmail.com)
12 | * @since v1.0.0
13 | */
14 | public class AppendGlobalParamsIntercept implements InterceptRequest {
15 | @Override
16 | public Request onInterceptRequest(Request request) {
17 | HashMap params = new HashMap<>();
18 | HashMap headers = new HashMap<>();
19 |
20 | headers.put("comm_global_custom_header1", "comm_custom_header1");
21 | headers.put("comm_global_custom_header2", "comm_custom_header2");
22 |
23 | params.put("comm_global_custom_params1", "comm_custom_params1");
24 | params.put("comm_global_custom_params2", "comm_custom_params2");
25 |
26 | for (Map.Entry old : request.params.entrySet()) {
27 | params.put(old.getKey(), old.getValue());
28 | }
29 |
30 | for (Map.Entry old : request.headers.entrySet()) {
31 | headers.put(old.getKey(), old.getValue());
32 | }
33 |
34 | Request clone = request.clone();
35 | clone.params.putAll(params);
36 | clone.headers.putAll(headers);
37 | return clone;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/mylibrary/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.novoda.bintray-release'
3 |
4 | android {
5 | compileSdkVersion 28
6 |
7 |
8 | defaultConfig {
9 | minSdkVersion 16
10 | targetSdkVersion 28
11 | versionCode 1
12 | versionName "1.0"
13 |
14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
15 |
16 | }
17 |
18 | buildTypes {
19 | release {
20 | minifyEnabled false
21 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
22 | }
23 | }
24 |
25 | }
26 |
27 | dependencies {
28 | implementation fileTree(dir: 'libs', include: ['*.jar'])
29 |
30 | implementation 'com.android.support:appcompat-v7:28.0.0'
31 | testImplementation 'junit:junit:4.12'
32 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
33 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
34 | }
35 |
36 | def siteUrl = 'http://xwcc.fun'
37 | publish {
38 | userOrg = 'quinnhuang'
39 | repoName = 'widget'
40 | groupId = 'com.xwdz'
41 | artifactId = 'EasyNetwork'
42 | publishVersion = '1.0.3'
43 | desc = 'Android native Http'//描述,不重要
44 | website = siteUrl//项目主页
45 | }
46 | tasks.withType(Javadoc) {//防止编码问题
47 | options.addStringOption('Xdoclint:none', '-quiet')
48 | options.addStringOption('encoding', 'UTF-8')
49 | options.addStringOption('charSet', 'UTF-8')
50 | }
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 28
5 | defaultConfig {
6 | applicationId "com.xwdz.httpsimple"
7 | minSdkVersion 19
8 | targetSdkVersion 28
9 | versionCode 1
10 | versionName "1.0"
11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | def RETROFIT2 = '2.5.0'
22 |
23 | dependencies {
24 | implementation fileTree(include: ['*.jar'], dir: 'libs')
25 | implementation 'com.android.support:appcompat-v7:28.0.0'
26 | implementation 'com.android.support.constraint:constraint-layout:1.1.3'
27 | testImplementation 'junit:junit:4.12'
28 | androidTestImplementation 'com.android.support.test:runner:1.0.2'
29 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
30 | implementation project(':mylibrary')
31 | // implementation 'com.xwdz:EasyNetwork:1.0.1-beta1'
32 | // implementation 'com.xwdz:SplashGlobally:0.0.1'
33 |
34 | implementation "com.squareup.retrofit2:retrofit:${RETROFIT2}"
35 | implementation "com.squareup.retrofit2:converter-gson:${RETROFIT2}"
36 | implementation "com.squareup.retrofit2:adapter-rxjava:${RETROFIT2}"
37 | implementation "io.reactivex:rxandroid:1.2.1"
38 | }
39 |
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/xwdz/http/thread/EasyThreadPools.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http.thread;
2 |
3 | import java.util.concurrent.Callable;
4 | import java.util.concurrent.ExecutorService;
5 | import java.util.concurrent.Executors;
6 | import java.util.concurrent.Future;
7 | import java.util.concurrent.ThreadFactory;
8 | import java.util.concurrent.atomic.AtomicInteger;
9 |
10 | /**
11 | * @author xingwei.huang (xwdz9989@gmail.com)
12 | * @since v1.0.0
13 | */
14 | public class EasyThreadPools {
15 |
16 | private static ExecutorService sDefaultExecutorService;
17 |
18 | private static AtomicInteger sAtomicInteger = new AtomicInteger();
19 |
20 | static {
21 |
22 | final ThreadFactory threadFactory = new ThreadFactory() {
23 | @Override
24 | public Thread newThread(Runnable r) {
25 | final Thread thread = new Thread(r);
26 | thread.setName("EasyNetwork#" + sAtomicInteger.getAndIncrement());
27 | return thread;
28 | }
29 | };
30 | sDefaultExecutorService = Executors.newCachedThreadPool(threadFactory);
31 | }
32 |
33 | public static void setDefaultExecutorService(ExecutorService defaultExecutorService) {
34 | sDefaultExecutorService = defaultExecutorService;
35 | }
36 |
37 |
38 | public static void executor(Runnable runnable) {
39 | sDefaultExecutorService.execute(runnable);
40 | }
41 |
42 | public static Future submit(Callable runnable) {
43 | return sDefaultExecutorService.submit(runnable);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xwdz/httpsimple/App.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.httpsimple;
2 |
3 | import android.app.Application;
4 |
5 | import com.xwdz.http.EasyNetwork;
6 | import com.xwdz.http.EasyNetworkConfig;
7 |
8 | /**
9 | * @author xingwei.huang (xwdz9989@gmail.com)
10 | * @since v1.0.0
11 | */
12 | public class App extends Application {
13 |
14 | @Override
15 | public void onCreate() {
16 | super.onCreate();
17 |
18 |
19 | EasyNetworkConfig config = new EasyNetworkConfig();
20 | config.addIntercepts(new AppendGlobalParamsIntercept());
21 | config.setOpenRetry(true);
22 | config.setRetryIntervalMillis(3000);
23 | // config.addIntercepts(new APISignatureIntercept());
24 | EasyNetwork.initializeConfig(config);
25 |
26 |
27 | // Retrofit retrofit = new Retrofit.Builder()
28 | // .baseUrl("11")
29 | // .client(okHttpClient)
30 | // .addConverterFactory(GsonConverterFactory.create())
31 | // .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
32 | // .build();
33 | //
34 | // retrofit.create(FeedApi.class).request("0")
35 | // .enqueue(new Callback() {
36 | // @Override
37 | // public void onResponse(Call call, Response response) {
38 | //
39 | // }
40 | //
41 | // @Override
42 | // public void onFailure(Call call, Throwable t) {
43 | //
44 | // }
45 | // });
46 |
47 |
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/xwdz/http/EasyNetwork.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http;
2 |
3 | import android.text.TextUtils;
4 |
5 | import com.xwdz.http.callback.IBaseEasyCallback;
6 | import com.xwdz.http.core.EasyRequestManager;
7 | import com.xwdz.http.core.Request;
8 |
9 | /**
10 | * @author xingwei.huang (xwdz9989@gmail.com)
11 | * @since v1.0.0
12 | */
13 | public class EasyNetwork {
14 |
15 |
16 | private static EasyRequestManager sEasyRequestManager = new EasyRequestManager();
17 | private static EasyNetworkConfig sConfig = new EasyNetworkConfig();
18 |
19 |
20 |
21 | private EasyNetwork() {
22 |
23 | }
24 |
25 | public static void initializeConfig(EasyNetworkConfig config) {
26 | sConfig = config;
27 | }
28 |
29 | public static EasyNetworkConfig getConfig() {
30 | return sConfig;
31 | }
32 |
33 | public static void sendRequest(Request request, IBaseEasyCallback baseEasyCallback) {
34 | if (request == null) {
35 | throw new NullPointerException("request == null");
36 | }
37 |
38 | if (TextUtils.isEmpty(request.url)) {
39 | throw new NullPointerException("url == null");
40 | }
41 |
42 | request.tag = request.tag == null ? request.url : request.tag;
43 |
44 |
45 | sEasyRequestManager.performRequest(sConfig, request, baseEasyCallback);
46 | }
47 |
48 | public static void cancelRequest(Object tag) {
49 | sEasyRequestManager.performCancelRequest(tag);
50 | }
51 |
52 | public static void cancelAll() {
53 | sEasyRequestManager.performCancelAll();
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
11 |
16 |
17 |
18 |
23 |
24 |
25 |
32 |
33 |
39 |
40 |
41 |
47 |
48 |
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/xwdz/http/EasyNetworkConfig.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http;
2 |
3 | import com.xwdz.http.callback.InterceptRequest;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | /**
9 | * @author xingwei.huang (xwdz9989@gmail.com)
10 | * @since v1.0.0
11 | */
12 | public class EasyNetworkConfig {
13 |
14 |
15 | public static boolean isDebug = true;
16 |
17 | private int connectTimeoutMillis = 15 * 1000;
18 | private int readTimeoutMillis = 15 * 1000;
19 |
20 | private List interceptRequests = new ArrayList<>();
21 | // 失败重试次数
22 | private int retryCount = 3;
23 | // 是否需要打开重试机制
24 | private boolean isOpenRetry = true;
25 | // 每次重试间隔时间
26 | private long retryIntervalMillis = 3000;
27 |
28 | public int getRetryCount() {
29 | return retryCount;
30 | }
31 |
32 | public void setRetryCount(int retryCount) {
33 | this.retryCount = retryCount;
34 | }
35 |
36 | public void addIntercepts(InterceptRequest interceptRequest) {
37 | this.interceptRequests.add(interceptRequest);
38 | }
39 |
40 | public long getRetryIntervalMillis() {
41 | return retryIntervalMillis;
42 | }
43 |
44 | public void setRetryIntervalMillis(long retryIntervalMillis) {
45 | this.retryIntervalMillis = retryIntervalMillis;
46 | }
47 |
48 | public List getInterceptRequests() {
49 | return interceptRequests;
50 | }
51 |
52 |
53 | public void setConnectTimeoutMillis(int connectTimeoutMillis) {
54 | this.connectTimeoutMillis = connectTimeoutMillis;
55 | }
56 |
57 | public void setReadTimeoutMillis(int readTimeoutMillis) {
58 | this.readTimeoutMillis = readTimeoutMillis;
59 | }
60 |
61 | public boolean isOpenRetry() {
62 | return isOpenRetry;
63 | }
64 |
65 | public void setOpenRetry(boolean openRetry) {
66 | isOpenRetry = openRetry;
67 | }
68 |
69 | public int getConnectTimeoutMillis() {
70 | return connectTimeoutMillis;
71 | }
72 |
73 | public int getReadTimeoutMillis() {
74 | return readTimeoutMillis;
75 | }
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/xwdz/http/callback/StringEasyCallbackImpl.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http.callback;
2 |
3 | import com.xwdz.http.Util;
4 | import com.xwdz.http.core.EasyCall;
5 |
6 | import java.io.ByteArrayOutputStream;
7 | import java.io.InputStream;
8 | import java.net.HttpURLConnection;
9 |
10 | /**
11 | * @author xingwei.huang (xwdz9989@gmail.com)
12 | * @since v1.0.0
13 | */
14 | public abstract class StringEasyCallbackImpl extends BaseEasyCallbackImpl {
15 |
16 | @Override
17 | public void onResponse(final EasyCall call, final HttpURLConnection httpURLConnection) {
18 | super.onResponse(call, httpURLConnection);
19 | InputStream is = null;
20 | ByteArrayOutputStream out = null;
21 | try {
22 | is = httpURLConnection.getInputStream();
23 | out = new ByteArrayOutputStream();
24 | byte[] buffer = new byte[2048];
25 | int len;
26 | while ((len = is.read(buffer)) != -1) {
27 | out.write(buffer, 0, len);
28 | }
29 | out.flush();
30 | out.close();
31 |
32 | final String result = new String(out.toByteArray());
33 |
34 | safeCall(new Runnable() {
35 | @Override
36 | public void run() {
37 | onSuccessful(result);
38 | }
39 | });
40 | } catch (final Throwable e) {
41 | e.printStackTrace();
42 | safeCall(new Runnable() {
43 | @Override
44 | public void run() {
45 | onFailure(call, e);
46 | }
47 | });
48 | } finally {
49 | Util.quietClose(is);
50 | Util.quietClose(out);
51 | safeCall(new Runnable() {
52 | @Override
53 | public void run() {
54 | onCompleted();
55 | }
56 | });
57 | }
58 | }
59 |
60 | @Override
61 | public void onFailure(EasyCall call, Throwable error) {
62 | safeCall(new Runnable() {
63 | @Override
64 | public void run() {
65 | onCompleted();
66 | }
67 | });
68 | }
69 |
70 | public abstract void onSuccessful(String data);
71 |
72 | public abstract void onCompleted();
73 | }
74 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/xwdz/http/callback/BaseEasyCallbackImpl.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http.callback;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 |
6 | import com.xwdz.http.Util;
7 | import com.xwdz.http.core.EasyCall;
8 | import com.xwdz.http.error.EasyHTTPException;
9 |
10 | import java.io.ByteArrayOutputStream;
11 | import java.io.IOException;
12 | import java.io.InputStream;
13 | import java.net.HttpURLConnection;
14 |
15 | /**
16 | * @author xingwei.huang (xwdz9989@gmail.com)
17 | * @since v1.0.0
18 | */
19 | public abstract class BaseEasyCallbackImpl implements IBaseEasyCallback {
20 |
21 | private static final String TAG = BaseEasyCallbackImpl.class.getSimpleName();
22 |
23 |
24 | protected Handler mHandler = new Handler(Looper.getMainLooper());
25 |
26 | private volatile boolean isCancelled = false;
27 |
28 | @Override
29 | public void onResponse(final EasyCall call, final HttpURLConnection httpURLConnection) {
30 | try {
31 | final int code = httpURLConnection.getResponseCode();
32 | if (HttpURLConnection.HTTP_OK != code) {
33 | safeCall(new Runnable() {
34 | @Override
35 | public void run() {
36 | onFailure(call, new Throwable(getErrorMessage(httpURLConnection.getErrorStream())));
37 | }
38 | });
39 | }
40 | } catch (IOException e) {
41 | e.printStackTrace();
42 | onFailure(call, new IOException(e));
43 | }
44 | }
45 |
46 | @Override
47 | public void onCancel() {
48 | isCancelled = true;
49 | }
50 |
51 | protected void checkIsCancelled() throws EasyHTTPException {
52 | if (isCancelled) {
53 | throw new EasyHTTPException("Cancelled Task", EasyHTTPException.Error.CANCEL_REQUEST);
54 | }
55 | }
56 |
57 | protected void safeCall(Runnable runnable) {
58 | if (Looper.getMainLooper() == Looper.myLooper()) {
59 | runnable.run();
60 | } else {
61 | mHandler.post(runnable);
62 | }
63 | }
64 |
65 | private String getErrorMessage(InputStream is) {
66 | ByteArrayOutputStream message = null;
67 | try {
68 | int length;
69 | byte[] buffered = new byte[2048];
70 | message = new ByteArrayOutputStream();
71 | while ((length = is.read(buffered)) > 0) {
72 | message.write(buffered, 0, length);
73 | }
74 | return message.toString("UTF-8");
75 | } catch (Throwable e) {
76 | e.printStackTrace();
77 | } finally {
78 | Util.quietClose(is);
79 | Util.quietClose(message);
80 | }
81 |
82 | return "";
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/xwdz/http/callback/FileEasyCallbackImpl.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http.callback;
2 |
3 | import com.xwdz.http.Util;
4 | import com.xwdz.http.core.EasyCall;
5 |
6 | import java.io.File;
7 | import java.io.FileOutputStream;
8 | import java.io.InputStream;
9 | import java.net.HttpURLConnection;
10 |
11 | /**
12 | * @author xingwei.huang (xwdz9989@gmail.com)
13 | * @since v1.0.0
14 | */
15 | public abstract class FileEasyCallbackImpl extends BaseEasyCallbackImpl {
16 |
17 | private String mPath;
18 |
19 | public FileEasyCallbackImpl(String path, String name) {
20 | mPath = path + name;
21 | }
22 |
23 | @Override
24 | public void onResponse(final EasyCall call, HttpURLConnection connection) {
25 | FileOutputStream out = null;
26 | InputStream is = null;
27 |
28 | try {
29 | if (connection.getResponseCode() == 200) {
30 | is = connection.getInputStream();
31 | File file = new File(mPath);
32 | out = new FileOutputStream(file);
33 | final int totalLen = connection.getContentLength();
34 | int curLen = 0;
35 | byte[] buffer = new byte[2048];
36 | int len;
37 | int percent = 0;
38 | while ((len = is.read(buffer)) != -1) {
39 | checkIsCancelled();
40 | out.write(buffer, 0, len);
41 | curLen += len;
42 | percent = (curLen * 100 / totalLen);
43 | final int finalCurLen = curLen;
44 | final int finalPercent = percent;
45 | Util.postToMain(new Runnable() {
46 | @Override
47 | public void run() {
48 | onProgressUpdated(finalCurLen, totalLen, finalPercent);
49 | }
50 | });
51 | }
52 | is.close();
53 | out.flush();
54 | out.close();
55 |
56 | Util.postToMain(new Runnable() {
57 | @Override
58 | public void run() {
59 | onSuccessful(new File(mPath));
60 | }
61 | });
62 | }
63 |
64 | } catch (final Throwable e) {
65 | e.printStackTrace();
66 | Util.postToMain(new Runnable() {
67 | @Override
68 | public void run() {
69 | onFailure(call, e);
70 | }
71 | });
72 |
73 | } finally {
74 | Util.quietClose(out);
75 | Util.quietClose(is);
76 | }
77 | }
78 |
79 | public abstract void onProgressUpdated(int currentLength, int totalLength, int percent);
80 |
81 | public abstract void onSuccessful(File file);
82 |
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/xwdz/http/core/HttpUrlConnection.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http.core;
2 |
3 | import android.webkit.URLUtil;
4 |
5 | import com.xwdz.http.EasyNetworkConfig;
6 | import com.xwdz.http.Util;
7 | import com.xwdz.http.callback.InterceptRequest;
8 |
9 | import java.io.OutputStream;
10 | import java.net.HttpURLConnection;
11 | import java.net.URL;
12 | import java.util.List;
13 | import java.util.Map;
14 |
15 | /**
16 | * @author xingwei.huang (xwdz9989@gmail.com)
17 | * @since v1.0.0
18 | */
19 | public class HttpUrlConnection {
20 |
21 | public static HttpURLConnection execute(Request request, EasyNetworkConfig config) throws Throwable {
22 | if (!URLUtil.isNetworkUrl(request.url)) {
23 | throw new Throwable("the url :" + request.url + " is not valid.");
24 | }
25 |
26 | List interceptRequestList = config.getInterceptRequests();
27 | for (InterceptRequest interceptRequest : interceptRequestList) {
28 | request = interceptRequest.onInterceptRequest(request);
29 | }
30 |
31 | switch (request.method) {
32 | case GET:
33 | return get(request, config);
34 | case POST:
35 | return post(request, config);
36 | }
37 | throw new Throwable("please use request method! ");
38 | }
39 |
40 |
41 | private static HttpURLConnection get(Request request, EasyNetworkConfig config) throws Throwable {
42 | try {
43 | String realUrl = request.url + Util.appendHttpParams(request.params, true);
44 |
45 | HttpURLConnection connection = (HttpURLConnection) new URL(realUrl).openConnection();
46 | connection.setRequestMethod(request.method.name());
47 | connection.setConnectTimeout(config.getConnectTimeoutMillis());
48 | connection.setReadTimeout(config.getReadTimeoutMillis());
49 |
50 | addHeader(connection, request.headers);
51 | connection.setUseCaches(false);
52 | connection.connect();
53 | return connection;
54 | } catch (Throwable e) {
55 | throw new Throwable(e);
56 | }
57 | }
58 |
59 |
60 | private static HttpURLConnection post(Request request, EasyNetworkConfig config) throws Throwable {
61 | OutputStream os = null;
62 | try {
63 |
64 | HttpURLConnection connection = (HttpURLConnection) new URL(request.url).openConnection();
65 | connection.setRequestMethod(request.method.name());
66 | connection.setConnectTimeout(config.getConnectTimeoutMillis());
67 | connection.setReadTimeout(config.getReadTimeoutMillis());
68 | connection.setDoOutput(true);
69 | connection.setUseCaches(false);
70 |
71 | addHeader(connection, request.headers);
72 | os = connection.getOutputStream();
73 | //todo postFile
74 | os.write(Util.formatPostParams(request.params).getBytes());
75 | connection.connect();
76 | return connection;
77 | } catch (Throwable e) {
78 | throw new Throwable(e);
79 | } finally {
80 | try {
81 | if (os != null) {
82 | os.flush();
83 | os.close();
84 | }
85 | } catch (Throwable e) {
86 | throw new Throwable(e);
87 | }
88 | }
89 | }
90 |
91 | private static void addHeader(HttpURLConnection connection, Map headers) {
92 | if (headers != null && !headers.isEmpty()) {
93 | for (Map.Entry entry : headers.entrySet()) {
94 | connection.addRequestProperty(entry.getKey(), entry.getValue());
95 | }
96 | }
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ### EasyNetwork
2 |
3 | 
4 |
5 | [](https://bintray.com/quinnhuang/widget/EasyNetwork/_latestVersion)
6 |
7 |
8 | #### 如果用的还行希望点个star,我会继续维护下去.
9 |
10 | ### 前言
11 | 开发中如果依赖了第三方Jar,而第三方Jar又需要依赖其他第三方库,如果是App开发还可以接受
12 | 但是如果是SDK开发者这种情况挺尴尬的,打成Jar后可能SDK体积会变的很大,又或者并不需要引入其他第三方库有点大材小用的感觉。
13 |
14 | `EasyNetwork`封装了一套Android原生的Http框架,提供了类`okHttp`拦截器机制,请求统一加密,响应统一解密,不需要额外引入任何库,体积小,强烈建议SDK开发者引入jar包.
15 |
16 | ### Download
17 |
18 | [作为SDK开发者,强烈建议下载jar包依赖,方便混淆 | Click download jar](https://bintray.com/quinnhuang/widget/EasyNetwork#files)
19 |
20 |
21 | ### 使用
22 |
23 |
24 | #### 自定义拦截器,统一加密、添加公共参数
25 |
26 | `EasyNetwork.initializeConfig()`必须传一个`EasyNetworkConfig(Context)`实例
27 |
28 | 在您的`Application#OnCreate`初始化各种配置.
29 |
30 | ```
31 | // Request拦截器
32 | public interface InterceptRequest {
33 |
34 | Request onInterceptRequest(Request request);
35 |
36 | }
37 | public class App extends Application {
38 |
39 | @Override
40 | public void onCreate() {
41 | super.onCreate();
42 |
43 | // 如果需要添加各种自定义配置,传入一个EasyNetworkConfig即可
44 | EasyNetworkConfig config = new EasyNetworkConfig();
45 | // 添加 公共参数拦截器
46 | config.addIntercepts(new AppendGlobalParamsIntercept());
47 | // 添加 统一加密所有请求
48 | config.addIntercepts(new APISignatureIntercept());
49 | // 重试次数
50 | config.setRetryCount(5)
51 | // 重试时间间隔
52 | config.setRetryIntervalMillis(3000);
53 |
54 | EasyNetwork.initializeConfig(config);
55 | }
56 |
57 | ```
58 |
59 | |SimpleIntercept|
60 | |:-:|
61 | |[AppendParamsIntercept](https://github.com/xwdz/EasyNetwork/blob/master/app/src/main/java/com/xwdz/httpsimple/AppendGlobalParamsIntercept.java)|
62 | |[APISignatureIntercept](https://github.com/xwdz/EasyNetwork/blob/master/app/src/main/java/com/xwdz/httpsimple/APISignatureIntercept.java)|
63 |
64 |
65 | **EasyNetworkConfig**
66 |
67 | |属性|说明|
68 | |:-:|:-:|
69 | |`setRetryCount(int)`|失败的重试次数|
70 | |`setOpenRetry(boolean)`|是否需要打开重试功能|
71 | |`setRetryIntervalMillis(long)`|每次重试的间隔时间|
72 | |`addIntercepts(InterceptRequest)`|自定义的各种拦截器|
73 |
74 | // 省略部分属性
75 |
76 | 使用`EasyNetwork.sendRequest(request,callback)`即可发送请求
77 |
78 | ```
79 |
80 | Request request = new Request.Builder()
81 | .url("ur")
82 | .post() // or get
83 | .tag("TAG")
84 | .addHeader("key","value")
85 | .addParam("key", "value")
86 | .build();
87 | // send Request
88 | EasyNetwork.sendRequest(request, new StringEasyCallbackImpl() {
89 | @Override
90 | public void onSuccessful(String data) {
91 | mLogView.setText(data);
92 | }
93 |
94 | @Override
95 | public void onFailure(EasyCall easyCall,Throwable error) {
96 | super.onFailure(easyCall, error);
97 | mLogView.setText(error.toString());
98 | }
99 |
100 | @Override
101 | public void onCompleted() {
102 | }
103 | });
104 |
105 | // cancel Request
106 | EasyNetwork.cancelRequest(request)
107 | ```
108 |
109 | ### 扩展Callback
110 | 继承`BaseEasyCallbackImpl`即可,完成自己解析、解密、逻辑接口。[Simple Code](https://github.com/xwdz/EasyNetwork/blob/master/mylibrary/src/main/java/com/xwdz/http/callback/FileEasyCallbackImpl.java)
111 |
112 |
113 | ### ChangedLog
114 |
115 | #### `1.0.3`
116 | - 不再使用单例
117 | - 不需要传入context
118 |
119 | #### `1.0.2`
120 | - 添加自动请求重定向机制
121 | - 添加自动重试机制
122 | - `IBaseEasyCallback#onResponse()#onFailure()`新增参数`EasyCall`类,`EasyCall`目前仅仅包装了一些请求信息.
123 | `
124 |
125 |
126 |
127 |
128 |
129 |
130 |
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/xwdz/http/Util.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http;
2 |
3 | import android.content.Context;
4 | import android.os.Environment;
5 | import android.os.Handler;
6 | import android.os.Looper;
7 | import android.util.Log;
8 |
9 | import org.json.JSONException;
10 | import org.json.JSONObject;
11 |
12 | import java.io.Closeable;
13 | import java.io.File;
14 | import java.io.IOException;
15 | import java.net.URLEncoder;
16 | import java.util.Iterator;
17 | import java.util.Map;
18 |
19 | /**
20 | * @author xingwei.huang (xwdz9989@gmail.com)
21 | * @since v1.0.0
22 | */
23 | public class Util {
24 |
25 | private static final Handler MAIN_UI_HREAD = new Handler(Looper.getMainLooper());
26 |
27 | public static void postToMain(Runnable runnable) {
28 | if (Looper.myLooper() == Looper.getMainLooper()) {
29 | runnable.run();
30 | } else {
31 | MAIN_UI_HREAD.post(runnable);
32 | }
33 | }
34 |
35 |
36 | public static void quietClose(Closeable closeable) {
37 | if (closeable != null) {
38 | try {
39 | closeable.close();
40 | } catch (IOException e) {
41 | e.printStackTrace();
42 | }
43 | }
44 | }
45 |
46 | public static String appendHttpParams(Map sLinkedHashMap, boolean isAppend) {
47 | Iterator keys = sLinkedHashMap.keySet().iterator();
48 | Iterator values = sLinkedHashMap.values().iterator();
49 | StringBuffer stringBuffer = new StringBuffer();
50 | if (isAppend) {
51 | stringBuffer.append("?");
52 | }
53 |
54 |
55 | for (int i = 0; i < sLinkedHashMap.size(); i++) {
56 | String value = null;
57 | try {
58 | value = URLEncoder.encode(values.next(), "utf-8");
59 | } catch (Exception e) {
60 | e.printStackTrace();
61 | }
62 |
63 | stringBuffer.append(keys.next() + "=" + value);
64 | if (i != sLinkedHashMap.size() - 1) {
65 | stringBuffer.append("&");
66 | }
67 | }
68 |
69 | return stringBuffer.toString();
70 | }
71 |
72 | public static File getDownloaderDir(Context context, String uniqueName) {
73 | String cachePath;
74 | if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
75 | || !Environment.isExternalStorageRemovable()) {
76 | cachePath = context.getExternalCacheDir().getPath();
77 | } else {
78 | cachePath = context.getCacheDir().getPath();
79 | }
80 | return new File(cachePath + File.separator + uniqueName);
81 | }
82 |
83 | public static String formatPostParams(Map params) {
84 | if (params.isEmpty()) {
85 | return "";
86 | }
87 |
88 | JSONObject jsonObject = new JSONObject();
89 | for (Map.Entry entry : params.entrySet()) {
90 | try {
91 | jsonObject.put(entry.getKey(), entry.getValue());
92 |
93 | } catch (JSONException e) {
94 | e.printStackTrace();
95 | }
96 | }
97 | return jsonObject.toString();
98 | }
99 |
100 |
101 | public static class Logger {
102 |
103 | public static final String TAG = EasyNetwork.class.getSimpleName();
104 |
105 | public static void w(String tag, String message) {
106 | if (EasyNetworkConfig.isDebug) {
107 | Log.w(TAG, "[" + tag + "] " + message);
108 | }
109 | }
110 |
111 | public static void e(String tag, String message) {
112 | if (EasyNetworkConfig.isDebug) {
113 | Log.e(TAG, "[" + tag + "]" + message);
114 | }
115 | }
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/xwdz/http/core/Request.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http.core;
2 |
3 | import com.xwdz.http.Util;
4 |
5 | import java.io.Serializable;
6 | import java.util.HashMap;
7 |
8 | /**
9 | * @author xingwei.huang (xwdz9989@gmail.com)
10 | * @since v1.0.0
11 | */
12 | public class Request implements Serializable, Cloneable {
13 |
14 | private static final long serialVersionUID = -6446819668525759443L;
15 |
16 | public String url;
17 | public Method method;
18 | public Object tag;
19 | public HashMap params;
20 | public HashMap headers;
21 |
22 | private Builder mBuilder;
23 |
24 |
25 | public Request(Builder builder) {
26 | this.mBuilder = builder;
27 | this.url = builder.url;
28 | this.method = builder.method;
29 | this.tag = builder.tag;
30 | this.params = builder.params;
31 | this.headers = builder.header;
32 | }
33 |
34 |
35 | public Request newRequest() {
36 | return new Request(mBuilder);
37 | }
38 |
39 | @Override
40 | public Request clone() {
41 | try {
42 | return (Request) super.clone();
43 | } catch (CloneNotSupportedException e) {
44 | e.printStackTrace();
45 | }
46 | return newRequest();
47 | }
48 |
49 | @Override
50 | public String toString() {
51 | return "url='" + url + '\'' +
52 | ", params=" + Util.formatPostParams(params) + ", headers=" + Util.formatPostParams(headers)
53 | ;
54 | }
55 |
56 | public static class Builder {
57 |
58 | String url;
59 | Method method;
60 | Object tag;
61 | HashMap params = new HashMap<>();
62 | HashMap header = new HashMap<>();
63 | int connectTimeoutMillis;
64 | int readTimeoutMills;
65 |
66 |
67 | public Builder setConnectTimeoutMillis(int connectTimeoutMillis) {
68 | this.connectTimeoutMillis = connectTimeoutMillis;
69 | return this;
70 | }
71 |
72 | public Builder setReadTimeoutMills(int readTimeoutMills) {
73 | this.readTimeoutMills = readTimeoutMills;
74 | return this;
75 | }
76 |
77 | public Builder url(String url) {
78 | this.url = url;
79 | get();
80 | return this;
81 | }
82 |
83 | public Builder get() {
84 | method = Method.GET;
85 | return this;
86 | }
87 |
88 | public Builder method(Method method) {
89 | this.method = method;
90 | return this;
91 | }
92 |
93 | public Builder post() {
94 | method = Method.POST;
95 | return this;
96 | }
97 |
98 | public Builder tag(Object tag) {
99 | this.tag = tag;
100 | return this;
101 | }
102 |
103 | public Builder addParam(String key, String value) {
104 | params.put(key, value);
105 | return this;
106 | }
107 |
108 | public Builder addHeader(String key, String value) {
109 | header.put(key, value);
110 | return this;
111 | }
112 |
113 | public Builder addParams(HashMap params) {
114 | this.params.putAll(params);
115 | return this;
116 | }
117 |
118 | public Builder addHeaders(HashMap params) {
119 | header.putAll(params);
120 | return this;
121 | }
122 |
123 | public Request build() {
124 | return new Request(this);
125 | }
126 | }
127 |
128 |
129 | public enum Method {
130 | GET("get"),
131 | POST("post");
132 |
133 | String name;
134 |
135 | Method(String name) {
136 | this.name = name;
137 | }
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/mylibrary/src/main/java/com/xwdz/http/thread/RequestTaskProxy.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.http.thread;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 | import android.text.TextUtils;
6 |
7 | import com.xwdz.http.EasyNetworkConfig;
8 | import com.xwdz.http.Util;
9 | import com.xwdz.http.callback.IBaseEasyCallback;
10 | import com.xwdz.http.core.EasyCall;
11 | import com.xwdz.http.core.HttpUrlConnection;
12 | import com.xwdz.http.core.Request;
13 |
14 | import java.net.HttpURLConnection;
15 | import java.util.concurrent.Callable;
16 | import java.util.concurrent.ExecutionException;
17 | import java.util.concurrent.FutureTask;
18 | import java.util.concurrent.atomic.AtomicBoolean;
19 | import java.util.concurrent.atomic.AtomicInteger;
20 |
21 | /**
22 | * @author xingwei.huang (xwdz9989@gmail.com)
23 | * @since v1.0.0
24 | */
25 | public class RequestTaskProxy {
26 |
27 | private static final String TAG = RequestTaskProxy.class.getSimpleName();
28 |
29 | private final AtomicBoolean mCancelled = new AtomicBoolean();
30 | private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
31 | private final AtomicBoolean isError = new AtomicBoolean();
32 | private final AtomicInteger mRetryCount = new AtomicInteger();
33 |
34 | private Handler mHandler = new Handler(Looper.getMainLooper());
35 |
36 | private volatile Request mRequest;
37 | private volatile IBaseEasyCallback mBaseEasyCallback;
38 | private EasyNetworkConfig mConfig;
39 | private FutureTask mFutureTask;
40 |
41 |
42 | private EasyCall mEasyCall;
43 |
44 |
45 | public RequestTaskProxy(EasyNetworkConfig config, Request request, IBaseEasyCallback baseEasyCallback) {
46 | this.mRequest = request;
47 | this.mBaseEasyCallback = baseEasyCallback;
48 | this.mConfig = config;
49 | this.mEasyCall = new EasyCall(mRequest);
50 | }
51 |
52 | public Request getRequest() {
53 | return mRequest;
54 | }
55 |
56 |
57 | public void start() {
58 | final Callable callable = new Callable() {
59 | @Override
60 | public HttpURLConnection call() {
61 | Util.Logger.w(TAG, "isRetry: [" + (mRetryCount.get() >= 1) + "]");
62 | Util.Logger.w(TAG, mRequest.toString());
63 | HttpURLConnection connection = null;
64 | try {
65 | mTaskInvoked.set(true);
66 | connection = HttpUrlConnection.execute(mRequest, mConfig);
67 | if (connection != null) {
68 | final int code = connection.getResponseCode();
69 | if (code >= 300 && code < 400) {
70 | //重定向
71 | if (!TextUtils.isEmpty(connection.getHeaderField("Location"))) {
72 | mRequest.url = connection.getHeaderField("Location");
73 | Util.Logger.w(TAG, "Redirect to url:" + mRequest.url);
74 | start();
75 | }
76 | }
77 | }
78 | mRetryCount.set(0);
79 | postResult(connection);
80 | Util.Logger.w(TAG, "Connection success!");
81 | return connection;
82 | } catch (final Throwable e) {
83 | callError(e);
84 | } finally {
85 | if (isError.get() && mConfig.isOpenRetry()) {
86 | if (mRetryCount.getAndIncrement() < mConfig.getRetryCount()) {
87 | Util.Logger.w(TAG, "RetryCount:" + mRetryCount.get());
88 | try {
89 | Thread.sleep(mConfig.getRetryIntervalMillis());
90 | } catch (InterruptedException e) {
91 | e.printStackTrace();
92 | }
93 | start();
94 |
95 | isError.set(false);
96 | mCancelled.set(false);
97 | }
98 | }
99 | }
100 | return connection;
101 | }
102 | };
103 |
104 |
105 | mFutureTask = new FutureTask(callable) {
106 | @Override
107 | protected void done() {
108 | super.done();
109 | try {
110 | get();
111 | } catch (ExecutionException e) {
112 | e.printStackTrace();
113 | } catch (InterruptedException e) {
114 | e.printStackTrace();
115 | callError(e);
116 | }
117 | }
118 | };
119 | EasyThreadPools.executor(mFutureTask);
120 | }
121 |
122 | private void postResult(final HttpURLConnection result) {
123 | boolean isInvoked = mTaskInvoked.get();
124 | if (isInvoked) {
125 | if (mBaseEasyCallback != null) {
126 | mBaseEasyCallback.onResponse(mEasyCall, result);
127 | }
128 | }
129 | }
130 |
131 | private void callError(final Throwable e) {
132 | isError.set(true);
133 | mCancelled.set(true);
134 | postMainThread(new Runnable() {
135 | @Override
136 | public void run() {
137 | if (mBaseEasyCallback != null) {
138 | mBaseEasyCallback.onFailure(mEasyCall, e);
139 | }
140 | }
141 | });
142 | }
143 |
144 |
145 | private void postMainThread(Runnable runnable) {
146 | mHandler.post(runnable);
147 | }
148 |
149 |
150 | public void cancel() {
151 | if (mFutureTask != null && !mFutureTask.isCancelled() && !mFutureTask.isDone()) {
152 | mFutureTask.cancel(true);
153 | Util.Logger.w(TAG, " Cancelled Http Task:" + mRequest.toString());
154 | }
155 |
156 | if (mBaseEasyCallback != null) {
157 | mBaseEasyCallback.onCancel();
158 | }
159 | }
160 | }
161 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/java/com/xwdz/httpsimple/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.xwdz.httpsimple;
2 |
3 | import android.os.Bundle;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.view.View;
6 | import android.widget.LinearLayout;
7 | import android.widget.TextView;
8 |
9 | import com.xwdz.http.EasyNetwork;
10 | import com.xwdz.http.Util;
11 | import com.xwdz.http.callback.FileEasyCallbackImpl;
12 | import com.xwdz.http.callback.StringEasyCallbackImpl;
13 | import com.xwdz.http.core.EasyCall;
14 | import com.xwdz.http.core.Request;
15 |
16 | import java.io.File;
17 |
18 | public class MainActivity extends AppCompatActivity {
19 |
20 |
21 | public static final String LINE_SEPARATOR = System.getProperty("line.separator");
22 |
23 | private TextView mLogView;
24 | private LinearLayout mProgressBar;
25 |
26 | @Override
27 | protected void onCreate(Bundle savedInstanceState) {
28 | super.onCreate(savedInstanceState);
29 | setContentView(R.layout.activity_main);
30 |
31 | mLogView = findViewById(R.id.logText);
32 | mProgressBar = findViewById(R.id.progressBar);
33 |
34 |
35 | findViewById(R.id.get).setOnClickListener(new View.OnClickListener() {
36 | @Override
37 | public void onClick(View v) {
38 | mProgressBar.setVisibility(View.VISIBLE);
39 | testGET();
40 | }
41 | });
42 |
43 |
44 | findViewById(R.id.post).setOnClickListener(new View.OnClickListener() {
45 | @Override
46 | public void onClick(View v) {
47 | mProgressBar.setVisibility(View.VISIBLE);
48 | testPOST();
49 | }
50 | });
51 |
52 | }
53 |
54 | @Override
55 | protected void onPause() {
56 | super.onPause();
57 | EasyNetwork.cancelRequest("TAG");
58 | }
59 |
60 | public void testGETDownloader() {
61 | Request request = new Request.Builder()
62 | .url("http://shouji.360tpcdn.com/150707/2ef5e16e0b8b3135aa714ad9b56b9a3d/com.happyelements.AndroidAnimal_25.apk")
63 | .tag("TAG")
64 | .build();
65 |
66 | EasyNetwork.sendRequest(request,
67 | new FileEasyCallbackImpl(
68 | Util.getDownloaderDir(this, "easy").getAbsolutePath(),
69 | "test.apk") {
70 |
71 | @Override
72 | public void onProgressUpdated(int currentLength, int totalLength, int percent) {
73 | mLogView.setText("" + percent + "%");
74 | }
75 |
76 | @Override
77 | public void onSuccessful(File file) {
78 | mLogView.setText(file.getAbsolutePath());
79 | }
80 |
81 | @Override
82 | public void onFailure(EasyCall easyCall, Throwable error) {
83 | mLogView.setText(error.toString());
84 | }
85 | });
86 |
87 |
88 | }
89 |
90 |
91 | public void testGET() {
92 | Request request = new Request.Builder()
93 | .url("http://47.106.223.246/test/get")
94 | .tag("TAG")
95 | .method(Request.Method.GET)
96 | .addParam("custom_test_param", "value")
97 | .addHeader("custom_test_header", "value")
98 | .build();
99 |
100 | EasyNetwork.sendRequest(request, new StringEasyCallbackImpl() {
101 | @Override
102 | public void onSuccessful(String data) {
103 | mLogView.setText(stringToJSON(data));
104 | }
105 |
106 | @Override
107 | public void onFailure(EasyCall easyCall, Throwable error) {
108 | super.onFailure(easyCall, error);
109 | mLogView.setText(error.toString());
110 | }
111 |
112 | @Override
113 | public void onCompleted() {
114 | mProgressBar.setVisibility(View.GONE);
115 | mLogView.setVisibility(View.VISIBLE);
116 | }
117 | });
118 | }
119 |
120 | public void testPOST() {
121 | Request request = new Request.Builder()
122 | .url("http://47.106.223.246/test/post")
123 | .post()
124 | .tag("TAG")
125 | .addParam("custom_test_param", "value")
126 | .addHeader("custom_test_header", "value")
127 | .build();
128 |
129 | EasyNetwork.sendRequest(request, new StringEasyCallbackImpl() {
130 | @Override
131 | public void onSuccessful(String data) {
132 | mLogView.setText(stringToJSON(data));
133 | }
134 |
135 | @Override
136 | public void onFailure(EasyCall easyCall, Throwable error) {
137 | super.onFailure(easyCall, error);
138 | mLogView.setText(error.toString());
139 | }
140 |
141 | @Override
142 | public void onCompleted() {
143 | mProgressBar.setVisibility(View.GONE);
144 | mLogView.setVisibility(View.VISIBLE);
145 | }
146 | });
147 | }
148 |
149 | public static String stringToJSON(String strJson) {
150 | // 计数tab的个数
151 | int tabNum = 0;
152 | StringBuffer jsonFormat = new StringBuffer();
153 | int length = strJson.length();
154 |
155 | char last = 0;
156 | for (int i = 0; i < length; i++) {
157 | char c = strJson.charAt(i);
158 | if (c == '{') {
159 | tabNum++;
160 | jsonFormat.append(c + "\n");
161 | jsonFormat.append(getSpaceOrTab(tabNum));
162 | } else if (c == '}') {
163 | tabNum--;
164 | jsonFormat.append("\n");
165 | jsonFormat.append(getSpaceOrTab(tabNum));
166 | jsonFormat.append(c);
167 | } else if (c == ',') {
168 | jsonFormat.append(c + "\n");
169 | jsonFormat.append(getSpaceOrTab(tabNum));
170 | } else if (c == ':') {
171 | jsonFormat.append(c + " ");
172 | } else if (c == '[') {
173 | tabNum++;
174 | char next = strJson.charAt(i + 1);
175 | if (next == ']') {
176 | jsonFormat.append(c);
177 | } else {
178 | jsonFormat.append(c + "\n");
179 | jsonFormat.append(getSpaceOrTab(tabNum));
180 | }
181 | } else if (c == ']') {
182 | tabNum--;
183 | if (last == '[') {
184 | jsonFormat.append(c);
185 | } else {
186 | jsonFormat.append("\n" + getSpaceOrTab(tabNum) + c);
187 | }
188 | } else {
189 | jsonFormat.append(c);
190 | }
191 | last = c;
192 | }
193 | return jsonFormat.toString();
194 | }
195 |
196 | private static String getSpaceOrTab(int tabNum) {
197 | StringBuffer sbTab = new StringBuffer();
198 | for (int i = 0; i < tabNum; i++) {
199 | sbTab.append('\t');
200 | }
201 | return sbTab.toString();
202 | }
203 | }
204 |
--------------------------------------------------------------------------------