├── .gitignore
├── .idea
├── compiler.xml
├── copyright
│ └── profiles_settings.xml
├── encodings.xml
├── gradle.xml
├── misc.xml
├── modules.xml
└── runConfigurations.xml
├── README.md
├── README.md.bak
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── sampleurlhttp
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── guozheng
│ │ └── sampleurlhttp
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── guozheng
│ │ │ └── sampleurlhttp
│ │ │ └── MainActivity.java
│ └── res
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── guozheng
│ └── sampleurlhttp
│ └── ExampleUnitTest.java
├── settings.gradle
└── urlhttputils
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
├── androidTest
└── java
│ └── com
│ └── guozheng
│ └── urlhttputils
│ └── ExampleInstrumentedTest.java
├── main
├── AndroidManifest.xml
├── java
│ └── com
│ │ └── guozheng
│ │ └── urlhttputils
│ │ ├── MainActivity.java
│ │ └── urlhttp
│ │ ├── CallBackUtil.java
│ │ ├── RealRequest.java
│ │ ├── RealResponse.java
│ │ ├── RequestUtil.java
│ │ └── UrlHttpUtil.java
└── res
│ ├── layout
│ └── activity_main.xml
│ ├── mipmap-hdpi
│ └── ic_launcher.png
│ ├── mipmap-mdpi
│ └── ic_launcher.png
│ ├── mipmap-xhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxxhdpi
│ └── ic_launcher.png
│ ├── values-w820dp
│ └── dimens.xml
│ └── values
│ ├── colors.xml
│ ├── dimens.xml
│ ├── strings.xml
│ └── styles.xml
└── test
└── java
└── com
└── guozheng
└── urlhttputils
└── ExampleUnitTest.java
/.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 |
--------------------------------------------------------------------------------
/.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 |
18 |
19 |
--------------------------------------------------------------------------------
/.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.8
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guozhengXia/UrlHttpUtils/6c4f060150efddbe1d7b28d271e39103ab9f76a2/README.md
--------------------------------------------------------------------------------
/README.md.bak:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guozhengXia/UrlHttpUtils/6c4f060150efddbe1d7b28d271e39103ab9f76a2/README.md.bak
--------------------------------------------------------------------------------
/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.2.2'
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/guozhengXia/UrlHttpUtils/6c4f060150efddbe1d7b28d271e39103ab9f76a2/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
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-2.14.1-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 |
--------------------------------------------------------------------------------
/sampleurlhttp/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/sampleurlhttp/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.3"
6 |
7 | defaultConfig {
8 | applicationId "com.guozheng.sampleurlhttp"
9 | minSdkVersion 16
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 |
14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
15 |
16 | }
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 | }
24 |
25 | dependencies {
26 | compile fileTree(dir: 'libs', include: ['*.jar'])
27 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
28 | exclude group: 'com.android.support', module: 'support-annotations'
29 | })
30 | compile 'com.android.support:appcompat-v7:23.2.1'
31 | testCompile 'junit:junit:4.12'
32 |
33 | compile project(':urlhttputils')
34 | }
35 |
--------------------------------------------------------------------------------
/sampleurlhttp/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 D:\develop\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 |
--------------------------------------------------------------------------------
/sampleurlhttp/src/androidTest/java/com/guozheng/sampleurlhttp/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.guozheng.sampleurlhttp;
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("com.guozheng.sampleurlhttp", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/sampleurlhttp/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/sampleurlhttp/src/main/java/com/guozheng/sampleurlhttp/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.guozheng.sampleurlhttp;
2 |
3 | import android.support.v7.app.AppCompatActivity;
4 | import android.os.Bundle;
5 | import android.util.Log;
6 | import android.view.View;
7 | import android.widget.Toast;
8 |
9 | import com.guozheng.urlhttputils.urlhttp.CallBackUtil;
10 | import com.guozheng.urlhttputils.urlhttp.UrlHttpUtil;
11 |
12 | import java.util.HashMap;
13 |
14 | public class MainActivity extends AppCompatActivity {
15 |
16 | @Override
17 | protected void onCreate(Bundle savedInstanceState) {
18 | super.onCreate(savedInstanceState);
19 | setContentView(R.layout.activity_main);
20 | }
21 |
22 | public void click(View v){
23 | getData();
24 |
25 | //postData();
26 |
27 | }
28 |
29 | private void postData() {
30 | String url = "https://www.baidu.com/";
31 | HashMap paramsMap = new HashMap<>();
32 | paramsMap.put("title","title");
33 | paramsMap.put("desc","desc");
34 | UrlHttpUtil.post(url, paramsMap, new CallBackUtil.CallBackString() {
35 | @Override
36 | public void onFailure(int code, String errorMessage) {
37 |
38 | }
39 |
40 | @Override
41 | public void onResponse(String response) {
42 | Toast.makeText(MainActivity.this,"Success",Toast.LENGTH_SHORT).show();
43 | Log.d("kwwl",response);
44 | }
45 | });
46 | }
47 |
48 | private void getData() {
49 | String url = "https://www.baidu.com/";
50 | UrlHttpUtil.get(url, new CallBackUtil.CallBackString() {
51 | @Override
52 | public void onFailure(int code, String errorMessage) {
53 |
54 | }
55 |
56 | @Override
57 | public void onResponse(String response) {
58 | Toast.makeText(MainActivity.this,"Success",Toast.LENGTH_SHORT).show();
59 | Log.d("kwwl",response);
60 | }
61 | });
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/sampleurlhttp/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
17 |
18 |
23 |
24 |
--------------------------------------------------------------------------------
/sampleurlhttp/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guozhengXia/UrlHttpUtils/6c4f060150efddbe1d7b28d271e39103ab9f76a2/sampleurlhttp/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sampleurlhttp/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guozhengXia/UrlHttpUtils/6c4f060150efddbe1d7b28d271e39103ab9f76a2/sampleurlhttp/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sampleurlhttp/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guozhengXia/UrlHttpUtils/6c4f060150efddbe1d7b28d271e39103ab9f76a2/sampleurlhttp/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sampleurlhttp/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guozhengXia/UrlHttpUtils/6c4f060150efddbe1d7b28d271e39103ab9f76a2/sampleurlhttp/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sampleurlhttp/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guozhengXia/UrlHttpUtils/6c4f060150efddbe1d7b28d271e39103ab9f76a2/sampleurlhttp/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sampleurlhttp/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/sampleurlhttp/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/sampleurlhttp/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/sampleurlhttp/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | SampleUrlHttp
3 |
4 |
--------------------------------------------------------------------------------
/sampleurlhttp/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/sampleurlhttp/src/test/java/com/guozheng/sampleurlhttp/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.guozheng.sampleurlhttp;
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 ':urlhttputils', ':sampleurlhttp'
2 |
--------------------------------------------------------------------------------
/urlhttputils/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/urlhttputils/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.3"
6 |
7 | defaultConfig {
8 | minSdkVersion 16
9 | targetSdkVersion 23
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:23.2.1'
30 | testCompile 'junit:junit:4.12'
31 | }
32 |
--------------------------------------------------------------------------------
/urlhttputils/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 D:\develop\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 |
--------------------------------------------------------------------------------
/urlhttputils/src/androidTest/java/com/guozheng/urlhttputils/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.guozheng.urlhttputils;
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("com.guozheng.urlhttputils", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/urlhttputils/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/urlhttputils/src/main/java/com/guozheng/urlhttputils/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.guozheng.urlhttputils;
2 |
3 | import android.support.v7.app.AppCompatActivity;
4 | import android.os.Bundle;
5 |
6 | public class MainActivity extends AppCompatActivity {
7 |
8 | @Override
9 | protected void onCreate(Bundle savedInstanceState) {
10 | super.onCreate(savedInstanceState);
11 | setContentView(R.layout.activity_main);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/urlhttputils/src/main/java/com/guozheng/urlhttputils/urlhttp/CallBackUtil.java:
--------------------------------------------------------------------------------
1 | package com.guozheng.urlhttputils.urlhttp;
2 |
3 | import android.graphics.Bitmap;
4 | import android.graphics.BitmapFactory;
5 | import android.os.Handler;
6 | import android.os.Looper;
7 | import android.widget.ImageView;
8 |
9 | import java.io.BufferedReader;
10 | import java.io.ByteArrayOutputStream;
11 | import java.io.File;
12 | import java.io.FileOutputStream;
13 | import java.io.IOException;
14 | import java.io.InputStream;
15 | import java.io.InputStreamReader;
16 |
17 | /**
18 | * Created by fighting on 2017/4/7.
19 | */
20 |
21 | public abstract class CallBackUtil {
22 | static Handler mMainHandler = new Handler(Looper.getMainLooper());
23 |
24 |
25 | public void onProgress(float progress, long total ){}
26 |
27 | void onError(final RealResponse response){
28 |
29 | final String errorMessage;
30 | if(response.inputStream != null){
31 | errorMessage = getRetString(response.inputStream);
32 | }else if(response.errorStream != null) {
33 | errorMessage = getRetString(response.errorStream);
34 | }else if(response.exception != null) {
35 | errorMessage = response.exception.getMessage();
36 | }else {
37 | errorMessage = "";
38 | }
39 | mMainHandler.post(new Runnable() {
40 | @Override
41 | public void run() {
42 | onFailure(response.code,errorMessage);
43 | }
44 | });
45 | }
46 | void onSeccess(RealResponse response){
47 | final T obj = onParseResponse(response);
48 | mMainHandler.post(new Runnable() {
49 | @Override
50 | public void run() {
51 | onResponse(obj);
52 | }
53 | });
54 | }
55 |
56 |
57 | /**
58 | * 解析response,执行在子线程
59 | */
60 | public abstract T onParseResponse(RealResponse response);
61 |
62 | /**
63 | * 访问网络失败后被调用,执行在UI线程
64 | */
65 | public abstract void onFailure(int code,String errorMessage);
66 |
67 | /**
68 | *
69 | * 访问网络成功后被调用,执行在UI线程
70 | */
71 | public abstract void onResponse(T response);
72 |
73 |
74 |
75 | public static abstract class CallBackDefault extends CallBackUtil {
76 | @Override
77 | public RealResponse onParseResponse(RealResponse response) {
78 | return response;
79 | }
80 | }
81 |
82 | public static abstract class CallBackString extends CallBackUtil {
83 | @Override
84 | public String onParseResponse(RealResponse response) {
85 | try {
86 | return getRetString(response.inputStream);
87 | } catch (Exception e) {
88 | throw new RuntimeException("failure");
89 | }
90 | }
91 | }
92 |
93 |
94 | public static abstract class CallBackBitmap extends CallBackUtil {
95 | private int mTargetWidth;
96 | private int mTargetHeight;
97 |
98 | public CallBackBitmap(){};
99 | public CallBackBitmap(int targetWidth,int targetHeight){
100 | mTargetWidth = targetWidth;
101 | mTargetHeight = targetHeight;
102 | };
103 | public CallBackBitmap(ImageView imageView){
104 | int width = imageView.getWidth();
105 | int height = imageView.getHeight();
106 | if(width <=0 || height <=0){
107 | throw new RuntimeException("无法获取ImageView的width或height");
108 | }
109 | mTargetWidth = width;
110 | mTargetHeight = height;
111 | };
112 | @Override
113 | public Bitmap onParseResponse(RealResponse response) {
114 | if(mTargetWidth ==0 || mTargetHeight == 0){
115 | return BitmapFactory.decodeStream(response.inputStream);
116 | }else {
117 | return getZoomBitmap( response.inputStream);
118 | }
119 | }
120 |
121 | /**
122 | * 压缩图片,避免OOM异常
123 | */
124 | private Bitmap getZoomBitmap(InputStream inputStream) {
125 | byte[] data = null;
126 | try {
127 | data = input2byte(inputStream);
128 | } catch (IOException e) {
129 | e.printStackTrace();
130 | }
131 | BitmapFactory.Options options = new BitmapFactory.Options();
132 | options.inJustDecodeBounds = true;
133 |
134 | BitmapFactory.decodeByteArray(data,0,data.length,options);
135 | int picWidth = options.outWidth;
136 | int picHeight = options.outHeight;
137 | int sampleSize = 1;
138 | int heightRatio = (int) Math.floor((float) picWidth / (float) mTargetWidth);
139 | int widthRatio = (int) Math.floor((float) picHeight / (float) mTargetHeight);
140 | if (heightRatio > 1 || widthRatio > 1){
141 | sampleSize = Math.max(heightRatio,widthRatio);
142 | }
143 | options.inSampleSize = sampleSize;
144 | options.inJustDecodeBounds = false;
145 | Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length,options);
146 |
147 | if(bitmap == null){
148 | throw new RuntimeException("Failed to decode stream.");
149 | }
150 | return bitmap;
151 | }
152 | }
153 |
154 | public static final byte[] input2byte(InputStream inStream)
155 | throws IOException {
156 | ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
157 | byte[] buff = new byte[100];
158 | int rc = 0;
159 | while ((rc = inStream.read(buff, 0, 100)) > 0) {
160 | swapStream.write(buff, 0, rc);
161 | }
162 | byte[] in2b = swapStream.toByteArray();
163 | return in2b;
164 | }
165 |
166 | /**
167 | * 下载文件时的回调类
168 | */
169 | public static abstract class CallBackFile extends CallBackUtil {
170 |
171 | private final String mDestFileDir;
172 | private final String mdestFileName;
173 |
174 | /**
175 | *
176 | * @param destFileDir:文件目录
177 | * @param destFileName:文件名
178 | */
179 | public CallBackFile(String destFileDir, String destFileName){
180 | mDestFileDir = destFileDir;
181 | mdestFileName = destFileName;
182 | }
183 | @Override
184 | public File onParseResponse(RealResponse response) {
185 |
186 | InputStream is = null;
187 | byte[] buf = new byte[1024*8];
188 | int len = 0;
189 | FileOutputStream fos = null;
190 | try{
191 | is = response.inputStream;
192 | final long total = response.contentLength;
193 |
194 | long sum = 0;
195 |
196 | File dir = new File(mDestFileDir);
197 | if (!dir.exists()){
198 | dir.mkdirs();
199 | }
200 | File file = new File(dir, mdestFileName);
201 | fos = new FileOutputStream(file);
202 | while ((len = is.read(buf)) != -1){
203 | sum += len;
204 | fos.write(buf, 0, len);
205 | final long finalSum = sum;
206 | mMainHandler.post(new Runnable() {
207 | @Override
208 | public void run() {
209 | onProgress(finalSum * 100.0f / total,total);
210 | }
211 | });
212 | }
213 | fos.flush();
214 |
215 | return file;
216 |
217 | } catch (Exception e) {
218 | e.printStackTrace();
219 | } finally{
220 | try{
221 | fos.close();
222 | if (is != null) is.close();
223 | } catch (IOException e){
224 | }
225 | try{
226 | if (fos != null) fos.close();
227 | } catch (IOException e){
228 | }
229 |
230 | }
231 | return null;
232 | }
233 | }
234 |
235 |
236 | private static String getRetString(InputStream is) {
237 | String buf;
238 | try {
239 | BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
240 | StringBuilder sb = new StringBuilder();
241 | String line = "";
242 | while ((line = reader.readLine()) != null) {
243 | sb.append(line + "\n");
244 | }
245 | is.close();
246 | buf = sb.toString();
247 | return buf;
248 |
249 | } catch (Exception e) {
250 | return null;
251 | }
252 | }
253 |
254 | }
255 |
--------------------------------------------------------------------------------
/urlhttputils/src/main/java/com/guozheng/urlhttputils/urlhttp/RealRequest.java:
--------------------------------------------------------------------------------
1 | package com.guozheng.urlhttputils.urlhttp;
2 |
3 | import android.text.TextUtils;
4 |
5 | import java.io.BufferedWriter;
6 | import java.io.DataOutputStream;
7 | import java.io.File;
8 | import java.io.FileInputStream;
9 | import java.io.IOException;
10 | import java.io.OutputStreamWriter;
11 | import java.net.HttpURLConnection;
12 | import java.net.ProtocolException;
13 | import java.net.URL;
14 | import java.util.List;
15 | import java.util.Map;
16 |
17 | /**
18 | * Created by fighting on 2017/4/24.
19 | */
20 |
21 | class RealRequest {
22 | private static final String BOUNDARY = java.util.UUID.randomUUID().toString();
23 | private static final String TWO_HYPHENS = "--";
24 | private static final String LINE_END = "\r\n";
25 |
26 | /**
27 | * get请求
28 | */
29 | RealResponse getData(String requestURL, Map headerMap){
30 | HttpURLConnection conn = null;
31 | try {
32 | conn= getHttpURLConnection(requestURL,"GET");
33 | conn.setDoInput(true);
34 | if(headerMap != null){
35 | setHeader(conn,headerMap);
36 | }
37 | conn.connect();
38 | return getRealResponse(conn);
39 | } catch (Exception e) {
40 | return getExceptonResponse(conn, e);
41 | }
42 | }
43 |
44 | /**
45 | * post请求
46 | */
47 | RealResponse postData(String requestURL, String body, String bodyType, Map headerMap) {
48 | HttpURLConnection conn = null;
49 | try {
50 | conn = getHttpURLConnection(requestURL,"POST");
51 | conn.setDoOutput(true);//可写出
52 | conn.setDoInput(true);//可读入
53 | conn.setUseCaches(false);//不是有缓存
54 | if(!TextUtils.isEmpty(bodyType)) {
55 | conn.setRequestProperty("Content-Type", bodyType);
56 | }
57 | if(headerMap != null){
58 | setHeader(conn,headerMap);//请求头必须放在conn.connect()之前
59 | }
60 | conn.connect();// 连接,以上所有的请求配置必须在这个API调用之前
61 | if(!TextUtils.isEmpty(body)) {
62 | BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
63 | writer.write(body);
64 | writer.close();
65 | }
66 | return getRealResponse(conn);
67 | } catch (Exception e) {
68 | return getExceptonResponse(conn, e);
69 | }
70 | }
71 |
72 | /**
73 | * 上传文件
74 | */
75 | RealResponse uploadFile(String requestURL, File file,List fileList,Map fileMap,String fileKey,String fileType,Map paramsMap,Map headerMap,CallBackUtil callBack) {
76 | HttpURLConnection conn = null;
77 | try {
78 | conn = getHttpURLConnection(requestURL,"POST");
79 | setConnection(conn);
80 | if(headerMap != null){
81 | setHeader(conn,headerMap);
82 | }
83 | conn.connect();
84 | DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
85 | if (paramsMap != null) {
86 | outputStream.write(getParamsString(paramsMap).getBytes());//上传参数
87 | outputStream.flush();
88 | }
89 | if(file != null) {
90 | writeFile(file, fileKey, fileType, outputStream,callBack);//上传文件
91 | }else if(fileList != null){
92 | for (File f : fileList){
93 | writeFile(f, fileKey, fileType, outputStream,null);
94 | }
95 | }else if(fileMap != null){
96 | for (String key : fileMap.keySet()){
97 | writeFile(fileMap.get(key), key, fileType, outputStream,null);
98 | }
99 | }
100 | byte[] endData = (LINE_END + TWO_HYPHENS + BOUNDARY + TWO_HYPHENS + LINE_END).getBytes();//写结束标记位
101 | outputStream.write(endData);
102 | outputStream.flush();
103 | return getRealResponse(conn);
104 | } catch (Exception e) {
105 | return getExceptonResponse(conn,e);
106 | }
107 | }
108 |
109 | /**
110 | * 得到Connection对象,并进行一些设置
111 | */
112 | private HttpURLConnection getHttpURLConnection(String requestURL,String requestMethod) throws IOException {
113 | URL url = new URL(requestURL);
114 | HttpURLConnection conn = (HttpURLConnection) url.openConnection();
115 | conn.setConnectTimeout(10*1000);
116 | conn.setReadTimeout(15*1000);
117 | conn.setRequestMethod(requestMethod);
118 | return conn;
119 | }
120 |
121 | /**
122 | * 设置请求头
123 | */
124 | private void setHeader(HttpURLConnection conn, Map headerMap) {
125 | if(headerMap != null){
126 | for (String key: headerMap.keySet()){
127 | conn.setRequestProperty(key, headerMap.get(key));
128 | }
129 | }
130 | }
131 |
132 | /**
133 | * 上传文件时设置Connection参数
134 | */
135 | private void setConnection(HttpURLConnection conn) throws ProtocolException {
136 | conn.setDoOutput(true);
137 | conn.setDoInput(true);
138 | conn.setUseCaches(false);
139 | conn.setRequestProperty("Connection", "Keep-Alive");
140 | conn.setRequestProperty("Charset", "UTF-8");
141 | conn.setRequestProperty("Content-Type","multipart/form-data; BOUNDARY=" + BOUNDARY);
142 | }
143 |
144 | /**
145 | * 上传文件时得到拼接的参数字符串
146 | */
147 | private String getParamsString(Map paramsMap) {
148 | StringBuffer strBuf = new StringBuffer();
149 | for (String key : paramsMap.keySet()){
150 | strBuf.append(TWO_HYPHENS);
151 | strBuf.append(BOUNDARY);
152 | strBuf.append(LINE_END);
153 | strBuf.append("Content-Disposition: form-data; name=\"" + key + "\"");
154 | strBuf.append(LINE_END);
155 |
156 | strBuf.append("Content-Type: " + "text/plain" );
157 | strBuf.append(LINE_END);
158 | strBuf.append("Content-Lenght: "+paramsMap.get(key).length());
159 | strBuf.append(LINE_END);
160 | strBuf.append(LINE_END);
161 | strBuf.append(paramsMap.get(key));
162 | strBuf.append(LINE_END);
163 | }
164 | return strBuf.toString();
165 | }
166 |
167 | /**
168 | * 上传文件时写文件
169 | */
170 | private void writeFile(File file, String fileKey, String fileType, DataOutputStream outputStream, final CallBackUtil callBack) throws IOException {
171 | outputStream.write(getFileParamsString(file, fileKey, fileType).getBytes());
172 | outputStream.flush();
173 |
174 | FileInputStream inputStream = new FileInputStream(file);
175 | final long total = file.length();
176 | long sum = 0;
177 | byte[] buffer = new byte[1024*2];
178 | int length = -1;
179 | while ((length = inputStream.read(buffer)) != -1){
180 | outputStream.write(buffer,0,length);
181 | sum = sum + length;
182 | if(callBack != null){
183 | final long finalSum = sum;
184 | CallBackUtil.mMainHandler.post(new Runnable() {
185 | @Override
186 | public void run() {
187 | callBack.onProgress(finalSum * 100.0f / total,total);
188 | }
189 | });
190 | }
191 | }
192 | outputStream.flush();
193 | inputStream.close();
194 | }
195 |
196 | /**
197 | * 上传文件时得到一定格式的拼接字符串
198 | */
199 | private String getFileParamsString(File file, String fileKey, String fileType) {
200 | StringBuffer strBuf = new StringBuffer();
201 | strBuf.append(LINE_END);
202 | strBuf.append(TWO_HYPHENS);
203 | strBuf.append(BOUNDARY);
204 | strBuf.append(LINE_END);
205 | strBuf.append("Content-Disposition: form-data; name=\"" + fileKey + "\"; filename=\"" + file.getName() + "\"");
206 | strBuf.append(LINE_END);
207 | strBuf.append("Content-Type: " + fileType );
208 | strBuf.append(LINE_END);
209 | strBuf.append("Content-Lenght: "+file.length());
210 | strBuf.append(LINE_END);
211 | strBuf.append(LINE_END);
212 | return strBuf.toString();
213 | }
214 |
215 | /**
216 | * 当正常返回时,得到Response对象
217 | */
218 | private RealResponse getRealResponse(HttpURLConnection conn) throws IOException {
219 | RealResponse response = new RealResponse();
220 | response.code = conn.getResponseCode();
221 | response.contentLength = conn.getContentLength();
222 | response.inputStream = conn.getInputStream();
223 | response.errorStream = conn.getErrorStream();
224 | return response;
225 | }
226 |
227 | /**
228 | * 当发生异常时,得到Response对象
229 | */
230 | private RealResponse getExceptonResponse(HttpURLConnection conn, Exception e) {
231 | if(conn != null){
232 | conn.disconnect();
233 | }
234 | e.printStackTrace();
235 | RealResponse response = new RealResponse();
236 | response.exception = e;
237 | return response;
238 | }
239 |
240 | }
241 |
--------------------------------------------------------------------------------
/urlhttputils/src/main/java/com/guozheng/urlhttputils/urlhttp/RealResponse.java:
--------------------------------------------------------------------------------
1 | package com.guozheng.urlhttputils.urlhttp;
2 |
3 | import java.io.InputStream;
4 |
5 | /**
6 | * Created by fighting on 2017/4/24.
7 | */
8 |
9 | public class RealResponse {
10 | public InputStream inputStream;
11 | public InputStream errorStream;
12 | public int code;
13 | public long contentLength;
14 | public Exception exception;
15 | }
16 |
--------------------------------------------------------------------------------
/urlhttputils/src/main/java/com/guozheng/urlhttputils/urlhttp/RequestUtil.java:
--------------------------------------------------------------------------------
1 | package com.guozheng.urlhttputils.urlhttp;
2 |
3 | import android.text.TextUtils;
4 |
5 | import java.io.File;
6 | import java.io.UnsupportedEncodingException;
7 | import java.net.HttpURLConnection;
8 | import java.net.URLEncoder;
9 | import java.util.List;
10 | import java.util.Map;
11 |
12 | /**
13 | * Created by fighting on 2017/4/24.
14 | */
15 |
16 | class RequestUtil{
17 | private Thread mThread;
18 |
19 | /**
20 | * 一般的get请求或post请求
21 | */
22 | RequestUtil(String method,String url, Map paramsMap, Map headerMap, CallBackUtil callBack) {
23 | switch (method){
24 | case "GET":
25 | urlHttpGet(url,paramsMap,headerMap,callBack);
26 | break;
27 | case "POST":
28 | urlHttpPost(url,paramsMap,null,headerMap,callBack);
29 | break;
30 | }
31 | }
32 |
33 | /**
34 | * post请求,传递json格式数据。
35 | */
36 | RequestUtil(String url, String jsonStr, Map headerMap, CallBackUtil callBack) {
37 | urlHttpPost(url,null,jsonStr,headerMap,callBack);
38 | }
39 |
40 | /**
41 | * 上传文件
42 | */
43 | RequestUtil(String url, File file ,List fileList,Map fileMap,String fileKey,String fileType, Map paramsMap, Map headerMap,CallBackUtil callBack) {
44 | urlHttpUploadFile(url,file,fileList,fileMap,fileKey,fileType,paramsMap,headerMap,callBack);
45 | }
46 |
47 | /**
48 | * get请求
49 | */
50 | private void urlHttpGet(final String url, final Map paramsMap, final Map headerMap, final CallBackUtil callBack) {
51 | mThread = new Thread(new Runnable() {
52 | @Override
53 | public void run() {
54 | RealResponse response = new RealRequest().getData(getUrl(url,paramsMap),headerMap);
55 | if(response.code == HttpURLConnection.HTTP_OK){
56 | callBack.onSeccess(response);
57 | }else {
58 | callBack.onError(response);
59 | }
60 | }
61 |
62 | });
63 | }
64 |
65 | /**
66 | * post请求
67 | */
68 | private void urlHttpPost(final String url, final Map paramsMap, final String jsonStr, final Map headerMap, final CallBackUtil callBack) {
69 | mThread = new Thread(new Runnable() {
70 | @Override
71 | public void run() {
72 | RealResponse response = new RealRequest().postData(url, getPostBody(paramsMap,jsonStr),getPostBodyType(paramsMap,jsonStr),headerMap);
73 | if(response.code == HttpURLConnection.HTTP_OK){
74 | callBack.onSeccess(response);
75 | }else {
76 | callBack.onError(response);
77 | }
78 |
79 | }
80 |
81 | });
82 |
83 | }
84 |
85 | /**
86 | * 上传文件
87 | */
88 | private void urlHttpUploadFile(final String url, final File file , final List fileList, final Map fileMap, final String fileKey, final String fileType, final Map paramsMap, final Map headerMap, final CallBackUtil callBack) {
89 | mThread = new Thread(new Runnable() {
90 | @Override
91 | public void run() {
92 | RealResponse response = null;
93 | response = new RealRequest().uploadFile(url, file,fileList,fileMap,fileKey,fileType,paramsMap,headerMap,callBack);
94 | if(response.code == HttpURLConnection.HTTP_OK){
95 | callBack.onSeccess(response);
96 | }else {
97 | callBack.onError(response);
98 | }
99 | }
100 |
101 | });
102 | }
103 |
104 |
105 |
106 | /**
107 | * get请求,将键值对凭接到url上
108 | */
109 | private String getUrl(String path,Map paramsMap) {
110 | if(paramsMap != null){
111 | path = path+"?";
112 | for (String key: paramsMap.keySet()){
113 | path = path + key+"="+paramsMap.get(key)+"&";
114 | }
115 | path = path.substring(0,path.length()-1);
116 | }
117 | return path;
118 | }
119 |
120 | /**
121 | * 得到post请求的body
122 | */
123 | private String getPostBody(Map params,String jsonStr) {//throws UnsupportedEncodingException {
124 | if(params != null){
125 | return getPostBodyFormParameMap(params);
126 | }else if(!TextUtils.isEmpty(jsonStr)){
127 | return jsonStr;
128 | }
129 | return null;
130 | }
131 |
132 |
133 | /**
134 | * 根据键值对参数得到body
135 | */
136 | private String getPostBodyFormParameMap(Map params) {//throws UnsupportedEncodingException {
137 | StringBuilder result = new StringBuilder();
138 | boolean first = true;
139 | try {
140 | for (Map.Entry entry : params.entrySet()) {
141 | if (first)
142 | first = false;
143 | else
144 | result.append("&");
145 | result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
146 | result.append("=");
147 | result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
148 | }
149 | return result.toString();
150 | } catch (UnsupportedEncodingException e) {
151 | return null;
152 | }
153 |
154 | }
155 |
156 | /**
157 | * 得到bodyType
158 | */
159 | private String getPostBodyType(Map paramsMap, String jsonStr) {
160 | if(paramsMap != null){
161 | //return "text/plain";不知为什么这儿总是报错。目前暂不设置(20170424)
162 | return null;
163 | }else if(!TextUtils.isEmpty(jsonStr)){
164 | return "application/json;charset=utf-8";
165 | }
166 | return null;
167 | }
168 |
169 |
170 | /**
171 | * 开启子线程,调用run方法
172 | */
173 | void execute(){
174 | if(mThread != null){
175 | mThread.start();
176 | }
177 | }
178 |
179 |
180 |
181 |
182 |
183 | }
184 |
--------------------------------------------------------------------------------
/urlhttputils/src/main/java/com/guozheng/urlhttputils/urlhttp/UrlHttpUtil.java:
--------------------------------------------------------------------------------
1 | package com.guozheng.urlhttputils.urlhttp;
2 |
3 | import java.io.File;
4 | import java.util.List;
5 | import java.util.Map;
6 |
7 | /**
8 | * Created by fighting on 2017/4/24.
9 | */
10 |
11 | public class UrlHttpUtil {
12 | private static final String METHOD_GET = "GET";
13 | private static final String METHOD_POST = "POST";
14 |
15 | public static final String FILE_TYPE_FILE = "file/*";
16 | public static final String FILE_TYPE_IMAGE = "image/*";
17 | public static final String FILE_TYPE_AUDIO = "audio/*";
18 | public static final String FILE_TYPE_VIDEO = "video/*";
19 |
20 | /**
21 | * get请求
22 | * @param url:url
23 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。
24 | */
25 | public static void get(String url, CallBackUtil callBack) {
26 | get(url, null, null, callBack);
27 | }
28 |
29 | /**
30 | * get请求,可以传递参数
31 | * @param url:url
32 | * @param paramsMap:map集合,封装键值对参数
33 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。
34 | */
35 | public static void get(String url, Map paramsMap, CallBackUtil callBack) {
36 | get(url, paramsMap, null, callBack);
37 | }
38 |
39 | /**
40 | * get请求,可以传递参数
41 | * @param url:url
42 | * @param paramsMap:map集合,封装键值对参数
43 | * @param headerMap:map集合,封装请求头键值对
44 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。
45 | */
46 | public static void get(String url, Map paramsMap, Map headerMap, CallBackUtil callBack) {
47 | new RequestUtil(METHOD_GET, url, paramsMap, headerMap, callBack).execute();
48 | }
49 |
50 | /**
51 | * post请求
52 | * @param url:url
53 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。
54 | */
55 | public static void post(String url, CallBackUtil callBack) {
56 | post(url, null, callBack);
57 | }
58 |
59 | /**
60 | * post请求,可以传递参数
61 | * @param url:url
62 | * @param paramsMap:map集合,封装键值对参数
63 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。
64 | */
65 | public static void post(String url, Map paramsMap, CallBackUtil callBack) {
66 | post(url, paramsMap, null, callBack);
67 | }
68 |
69 | /**
70 | * post请求,可以传递参数
71 | * @param url:url
72 | * @param paramsMap:map集合,封装键值对参数
73 | * @param headerMap:map集合,封装请求头键值对
74 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。
75 | */
76 | public static void post(String url, Map paramsMap, Map headerMap, CallBackUtil callBack) {
77 | new RequestUtil(METHOD_POST,url,paramsMap,headerMap,callBack).execute();
78 | }
79 | /**
80 | * post请求,可以传递参数
81 | * @param url:url
82 | * @param jsonStr:json格式的键值对参数
83 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。
84 | */
85 | public static void postJson(String url, String jsonStr, CallBackUtil callBack) {
86 | postJson(url, jsonStr, null, callBack);
87 | }
88 |
89 | /**
90 | * post请求,可以传递参数
91 | * @param url:url
92 | * @param jsonStr:json格式的键值对参数
93 | * @param headerMap:map集合,封装请求头键值对
94 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。
95 | */
96 | public static void postJson(String url, String jsonStr, Map headerMap, CallBackUtil callBack) {
97 | new RequestUtil(url,jsonStr,headerMap,callBack).execute();
98 | }
99 |
100 |
101 |
102 |
103 | /**
104 | * post请求,上传单个文件
105 | * @param url:url
106 | * @param file:File对象
107 | * @param fileKey:上传参数时file对应的键
108 | * @param fileType:File类型,是image,video,audio,file
109 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。还可以重写onProgress方法,得到上传进度
110 | */
111 | public static void uploadFile(String url, File file, String fileKey, String fileType, CallBackUtil callBack) {
112 | uploadFile(url, file, fileKey,fileType, null, callBack);
113 | }
114 |
115 | /**
116 | * post请求,上传单个文件
117 | * @param url:url
118 | * @param file:File对象
119 | * @param fileKey:上传参数时file对应的键
120 | * @param fileType:File类型,是image,video,audio,file
121 | * @param paramsMap:map集合,封装键值对参数
122 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。还可以重写onProgress方法,得到上传进度
123 | */
124 | public static void uploadFile(String url, File file, String fileKey, String fileType, Map paramsMap, CallBackUtil callBack) {
125 | uploadFile(url, file,fileKey, fileType, paramsMap, null, callBack);
126 | }
127 |
128 | /**
129 | * post请求,上传单个文件
130 | * @param url:url
131 | * @param file:File对象
132 | * @param fileKey:上传参数时file对应的键
133 | * @param fileType:File类型,是image,video,audio,file
134 | * @param paramsMap:map集合,封装键值对参数
135 | * @param headerMap:map集合,封装请求头键值对
136 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。还可以重写onProgress方法,得到上传进度
137 | */
138 | public static void uploadFile(String url, File file, String fileKey, String fileType, Map paramsMap, Map headerMap, CallBackUtil callBack) {
139 | new RequestUtil(url,file,null,null,fileKey,fileType,paramsMap,headerMap,callBack).execute();
140 | }
141 |
142 |
143 | /**
144 | * post请求,上传多个文件,以list集合的形式
145 | * @param url:url
146 | * @param fileList:集合元素是File对象
147 | * @param fileKey:上传参数时fileList对应的键
148 | * @param fileType:File类型,是image,video,audio,file
149 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。
150 | */
151 | public static void uploadListFile(String url, List fileList, String fileKey, String fileType, CallBackUtil callBack) {
152 | uploadListFile(url, fileList, fileKey, fileType,null, callBack);
153 | }
154 |
155 | /**
156 | * post请求,上传多个文件,以list集合的形式
157 | * @param url:url
158 | * @param fileList:集合元素是File对象
159 | * @param fileKey:上传参数时fileList对应的键
160 | * @param fileType:File类型,是image,video,audio,file
161 | * @param paramsMap:map集合,封装键值对参数
162 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。
163 | */
164 | public static void uploadListFile(String url, List fileList, String fileKey, String fileType, Map paramsMap, CallBackUtil callBack) {
165 | uploadListFile(url, fileList, fileKey, fileType,paramsMap, null, callBack);
166 | }
167 |
168 | /**
169 | * post请求,上传多个文件,以list集合的形式
170 | * @param url:url
171 | * @param fileList:集合元素是File对象
172 | * @param fileKey:上传参数时fileList对应的键
173 | * @param fileType:File类型,是image,video,audio,file
174 | * @param paramsMap:map集合,封装键值对参数
175 | * @param headerMap:map集合,封装请求头键值对
176 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。
177 | */
178 | public static void uploadListFile(String url, List fileList, String fileKey, String fileType, Map paramsMap, Map headerMap, CallBackUtil callBack) {
179 | new RequestUtil(url,null,fileList,null,fileKey,fileType,paramsMap,headerMap,callBack).execute();
180 | }
181 |
182 | /**
183 | * post请求,上传多个文件,以map集合的形式
184 | * @param url:url
185 | * @param fileMap:集合key是File对象对应的键,集合value是File对象
186 | * @param fileType:File类型,是image,video,audio,file
187 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。
188 | */
189 | public static void uploadMapFile(String url, Map fileMap, String fileType, CallBackUtil callBack) {
190 | uploadMapFile(url, fileMap, fileType, null, callBack);
191 | }
192 |
193 | /**
194 | * post请求,上传多个文件,以map集合的形式
195 | * @param url:url
196 | * @param fileMap:集合key是File对象对应的键,集合value是File对象
197 | * @param fileType:File类型,是image,video,audio,file
198 | * @param paramsMap:map集合,封装键值对参数
199 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。
200 | */
201 | public static void uploadMapFile(String url, Map fileMap, String fileType, Map paramsMap, CallBackUtil callBack) {
202 | uploadMapFile(url, fileMap, fileType, paramsMap, null, callBack);
203 | }
204 |
205 | /**
206 | * post请求,上传多个文件,以map集合的形式
207 | * @param url:url
208 | * @param fileMap:集合key是File对象对应的键,集合value是File对象
209 | * @param fileType:File类型,是image,video,audio,file
210 | * @param paramsMap:map集合,封装键值对参数
211 | * @param headerMap:map集合,封装请求头键值对
212 | * @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。
213 | */
214 | public static void uploadMapFile(String url, Map fileMap, String fileType, Map paramsMap, Map headerMap, CallBackUtil callBack) {
215 | new RequestUtil(url,null,null,fileMap,null,fileType,paramsMap,headerMap,callBack).execute();
216 | }
217 |
218 | /**
219 | * 加载图片
220 | */
221 | public static void getBitmap(String url, CallBackUtil.CallBackBitmap callBack) {
222 | getBitmap(url, null, callBack);
223 | }
224 | /**
225 | * 加载图片,带参数
226 | */
227 | public static void getBitmap(String url,Map paramsMap, CallBackUtil.CallBackBitmap callBack) {
228 | get(url, paramsMap, null, callBack);
229 | }
230 |
231 | /**
232 | * 下载文件,不带参数
233 | */
234 | public static void downloadFile(String url, CallBackUtil.CallBackFile callBack) {
235 | downloadFile(url,null,callBack);
236 | }
237 |
238 | /**
239 | * 下载文件,带参数
240 | */
241 | public static void downloadFile(String url, Map paramsMap, CallBackUtil.CallBackFile callBack) {
242 | downloadFile(url, paramsMap, null, callBack);
243 | }
244 | /**
245 | * 下载文件,带参数,带请求头
246 | */
247 | public static void downloadFile(String url, Map paramsMap,Map headerMap, CallBackUtil.CallBackFile callBack) {
248 | get(url, paramsMap, headerMap, callBack);
249 | }
250 |
251 | }
252 |
--------------------------------------------------------------------------------
/urlhttputils/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
13 |
14 |
--------------------------------------------------------------------------------
/urlhttputils/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guozhengXia/UrlHttpUtils/6c4f060150efddbe1d7b28d271e39103ab9f76a2/urlhttputils/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/urlhttputils/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guozhengXia/UrlHttpUtils/6c4f060150efddbe1d7b28d271e39103ab9f76a2/urlhttputils/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/urlhttputils/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guozhengXia/UrlHttpUtils/6c4f060150efddbe1d7b28d271e39103ab9f76a2/urlhttputils/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/urlhttputils/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guozhengXia/UrlHttpUtils/6c4f060150efddbe1d7b28d271e39103ab9f76a2/urlhttputils/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/urlhttputils/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guozhengXia/UrlHttpUtils/6c4f060150efddbe1d7b28d271e39103ab9f76a2/urlhttputils/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/urlhttputils/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/urlhttputils/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/urlhttputils/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/urlhttputils/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | UrlHttpUtils
3 |
4 |
--------------------------------------------------------------------------------
/urlhttputils/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/urlhttputils/src/test/java/com/guozheng/urlhttputils/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.guozheng.urlhttputils;
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 | }
--------------------------------------------------------------------------------