├── .gitignore ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── liteHttp ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── me │ └── yourbay │ └── litehttp │ └── LiteHttp.java ├── sample ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── me │ │ └── yourbay │ │ └── litehttp_sample │ │ └── MainActivity.java │ └── res │ ├── layout │ └── activity_main.xml │ ├── mipmap-xxxhdpi │ └── ic_launcher.png │ ├── values-w820dp │ └── dimens.xml │ └── values │ ├── colors.xml │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Java class files 2 | *.class 3 | 4 | # generated files 5 | bin/ 6 | gen/ 7 | *.apk 8 | *.ap_ 9 | *.dex 10 | *.iml 11 | local.properties 12 | .classpath 13 | .project 14 | *.jar.properties 15 | project.properties 16 | .settings 17 | 18 | #temp files 19 | *.swp 20 | *~ 21 | *.iws 22 | *.ipr 23 | 24 | # lint 25 | lint.xml 26 | 27 | #android-app-pack 28 | auto.prop 29 | 30 | .DS_Store 31 | 32 | #annotation 33 | .factorypath 34 | 35 | #androidAnntation 36 | .apt_generated 37 | 38 | # Android Studio 39 | .idea/ 40 | .gradle/ 41 | build/ 42 | 43 | # Ignore Gradle GUI config 44 | gradle-app.setting 45 | 46 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 47 | !gradle-wrapper.jar 48 | 49 | 50 | 51 | *.index 52 | *.hprof 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## A lite android http library 2 | 3 | 如果你在开发一个应用或者某一个小模块,需要用到网络请求,可网络请求又不用那么频繁,而你又不想用一个太大的第三方库,比如`Volley` `Retrofit` 等。但是,又不想每次都封装一个网络请求库。那么你就可以用本项目。 4 | 5 | 它很小,只有一个文件,加上注释才300多行。Proguard后增加的体积基本可以忽略不计。假如你是一个视apk体积如生命的人,那么你完全不会想在一个网络请求很弱的项目中使用上面提到的lib。 6 | 7 | 当然,如果你有更好的想法,完全可以实现一个更好的,然后开源出来。方便大家,何乐不为。 8 | 9 | 所做的一切,完全都是为了让自己更`懒`。 10 | 11 | 生活不只眼前的苟且,还有。 12 | 13 | ## Features 14 | 15 | - body 16 | - Header 17 | - 各种请求 18 | - 上传文件 19 | - 下载文件 20 | - 请求重试 21 | - 读取进度 22 | 23 | ## TODO 24 | - 表单上传 25 | - 同时上传多文件 26 | 27 | ## Examples 28 | 29 | - 简单请求 30 | ```java 31 | new LiteHttp.Request().setUrl(url).connect() 32 | ``` 33 | - 实现下载 34 | ```java 35 | new LiteHttp.Request().setUrl(url)// 36 | .setStreamListener(new LiteHttp.StreamListener() { 37 | @Override 38 | public OutputStream getOutStream() { 39 | try { 40 | file.createNewFile(); 41 | return new BufferedOutputStream(new FileOutputStream(file), 16 * 1024); 42 | } catch (IOException e) { 43 | e.printStackTrace(); 44 | } 45 | return null; 46 | } 47 | @Override 48 | public InputStream getInStream() { 49 | return null; 50 | } 51 | })// 52 | .connect() 53 | ``` 54 | 55 | 56 | see more in module `sample` 57 | 58 | ## Download 59 | Get this via 60 | 61 | `Gradle`: 62 | ```groovy 63 | compile 'me.yourbay.basic:liteHttp:1.0' 64 | ``` 65 | 66 | `Maven`: 67 | ```xml 68 | 69 | me.yourbay.basic 70 | liteHttp 71 | 1.0 72 | pom 73 | 74 | ``` 75 | 76 | `Ivy`: 77 | ```xml 78 | 79 | 80 | 81 | ``` 82 | 83 | 84 | ## License 85 | 86 | Copyright 2016 LiteHttp 87 | 88 | Licensed under the Apache License, Version 2.0 (the "License"); 89 | you may not use this file except in compliance with the License. 90 | You may obtain a copy of the License at 91 | 92 | http://www.apache.org/licenses/LICENSE-2.0 93 | 94 | Unless required by applicable law or agreed to in writing, software 95 | distributed under the License is distributed on an "AS IS" BASIS, 96 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 97 | See the License for the specific language governing permissions and 98 | limitations under the License. 99 | 100 | 101 | -------------------------------------------------------------------------------- /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.0-alpha6' 9 | // NOTE: Do not place your application dependencies here; they belong 10 | // in the individual module build.gradle files 11 | } 12 | } 13 | 14 | allprojects { 15 | repositories { 16 | jcenter() 17 | } 18 | } 19 | 20 | task clean(type: Delete) { 21 | delete rootProject.buildDir 22 | } 23 | -------------------------------------------------------------------------------- /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 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hyongbai/liteHttpPrj/71535dc94a098cb69c07b7c98d2c017afdd98d17/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.10-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 | -------------------------------------------------------------------------------- /liteHttp/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /liteHttp/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.github.dcendents.android-maven' 3 | apply plugin: 'com.jfrog.bintray' 4 | buildscript { 5 | repositories { 6 | jcenter() 7 | } 8 | dependencies { 9 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' 10 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.0' 11 | } 12 | } 13 | android { 14 | compileSdkVersion 23 15 | buildToolsVersion "24.0.0" 16 | 17 | defaultConfig { 18 | minSdkVersion 14 19 | targetSdkVersion 23 20 | versionCode 1 21 | versionName "1.1" 22 | } 23 | buildTypes { 24 | release { 25 | minifyEnabled false 26 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 27 | } 28 | } 29 | } 30 | 31 | version = "1.1" 32 | group = "me.yourbay.basic" 33 | def gitUrl = 'git@github.com:hyongbai/LiteHttpPrj.git' 34 | def siteUrl = 'https://github.com/hyongbai/LiteHttpPrj' 35 | 36 | // 37 | install { 38 | repositories.mavenInstaller { 39 | pom { 40 | project { 41 | packaging 'aar' 42 | name 'simple http loader' 43 | url siteUrl 44 | licenses { 45 | license { 46 | name 'The Apache Software License, Version 2.0' 47 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 48 | } 49 | } 50 | developers { 51 | developer { 52 | id 'hyongbai' 53 | name 'hyongbai' 54 | email 'hyongbai@gmail.com' 55 | } 56 | } 57 | scm { 58 | connection gitUrl 59 | developerConnection gitUrl 60 | url siteUrl 61 | } 62 | } 63 | } 64 | } 65 | } 66 | 67 | task sourcesJar(type: Jar) { 68 | from android.sourceSets.main.java.srcDirs 69 | classifier = 'sources' 70 | } 71 | 72 | task javadoc(type: Javadoc) { 73 | source = android.sourceSets.main.java.srcDirs 74 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 75 | } 76 | 77 | task javadocJar(type: Jar, dependsOn: javadoc) { 78 | classifier = 'javadoc' 79 | from javadoc.destinationDir 80 | } 81 | 82 | artifacts { 83 | archives javadocJar 84 | archives sourcesJar 85 | } 86 | 87 | // config bintray 88 | def bintrayFile = file("${System.getenv('enims_keys')}/bintray_prop") 89 | println(bintrayFile) 90 | bintray { 91 | if (bintrayFile.exists()) { 92 | Properties properties = new Properties() 93 | properties.load(new FileInputStream(bintrayFile)) 94 | user = properties.getProperty("bintray.user") 95 | key = properties.getProperty("bintray.apikey") 96 | configurations = ['archives'] 97 | pkg { 98 | repo = "maven" 99 | name = "LiteHttpPrj" 100 | websiteUrl = siteUrl 101 | vcsUrl = gitUrl 102 | licenses = ["Apache-2.0"] 103 | publish = true 104 | } 105 | } 106 | } -------------------------------------------------------------------------------- /liteHttp/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 /Users/ram/android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /liteHttp/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /liteHttp/src/main/java/me/yourbay/litehttp/LiteHttp.java: -------------------------------------------------------------------------------- 1 | package me.yourbay.litehttp; 2 | 3 | import android.os.Build; 4 | import android.os.Handler; 5 | import android.os.Looper; 6 | import android.util.Log; 7 | 8 | import java.io.BufferedOutputStream; 9 | import java.io.ByteArrayOutputStream; 10 | import java.io.Closeable; 11 | import java.io.InputStream; 12 | import java.io.OutputStream; 13 | import java.net.HttpURLConnection; 14 | import java.net.URL; 15 | import java.net.URLConnection; 16 | import java.security.cert.X509Certificate; 17 | import java.util.HashMap; 18 | import java.util.Map; 19 | import java.util.Set; 20 | 21 | import javax.net.ssl.HttpsURLConnection; 22 | import javax.net.ssl.SSLContext; 23 | import javax.net.ssl.TrustManager; 24 | import javax.net.ssl.X509TrustManager; 25 | 26 | public class LiteHttp { 27 | private static boolean DEBUG = true; 28 | /* int params */ 29 | private final static int S_TIME_OUT = 30 * 1000; 30 | private final static int S_MAX_REPEAT_COUNT = 3; 31 | private final static int S_BUFF_SIZE = 16 * 1024; 32 | /* TrustManager */ 33 | private static final TrustManager[] INSECURE_TRUST_MANAGER = new TrustManager[]{ 34 | new X509TrustManager() { 35 | public X509Certificate[] getAcceptedIssuers() { 36 | return null; 37 | } 38 | 39 | public void checkClientTrusted(X509Certificate[] certs, String authType) { 40 | } 41 | 42 | public void checkServerTrusted(X509Certificate[] certs, String authType) { 43 | } 44 | } 45 | }; 46 | /* string params */ 47 | private final static String S_USER_AGENT = "Mozilla/5.0 (Linux; U; Android; en-ca;) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; 48 | /* default headers */ 49 | private final static Map S_DEFAULT_HEADERS = new HashMap<>(); 50 | 51 | static { 52 | S_DEFAULT_HEADERS.put("User-Agent", S_USER_AGENT); 53 | } 54 | 55 | private static Handler HANDLER = new Handler(Looper.getMainLooper()); 56 | 57 | private LiteHttp() { 58 | 59 | } 60 | 61 | /* basic methods */ 62 | 63 | public static HttpURLConnection beginConnect(String method, String urlStr, Map headers, boolean hasBody, int retryCount) throws Exception { 64 | URL url = new URL(urlStr); 65 | HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 66 | conn.setConnectTimeout(S_TIME_OUT); 67 | conn.setReadTimeout(S_TIME_OUT); 68 | conn.setDoInput(true); 69 | conn.setDoOutput(hasBody); 70 | /* ssl */ 71 | setSSL(conn); 72 | /* method */ 73 | conn.setRequestMethod(method); 74 | /* headers */ 75 | if (headers != null) { 76 | setHeader(conn, headers); 77 | } 78 | /* set default headers */ 79 | setHeader(conn, S_DEFAULT_HEADERS); 80 | /* connect */ 81 | if (repeatConnect(conn, retryCount) == retryCount) { 82 | conn.disconnect(); 83 | } 84 | return conn; 85 | } 86 | 87 | private static final void setSSL(URLConnection conn) { 88 | if (!(conn instanceof HttpsURLConnection)) { 89 | return; 90 | } 91 | try { 92 | HttpsURLConnection https = (HttpsURLConnection) conn; 93 | final String protocol = Build.VERSION.SDK_INT >= 16 ? "TLSv1.2" : "TLS"; 94 | SSLContext sslContext = SSLContext.getInstance(protocol, "AndroidOpenSSL"); 95 | sslContext.init(null, INSECURE_TRUST_MANAGER, new java.security.SecureRandom()); 96 | https.setSSLSocketFactory(sslContext.getSocketFactory()); 97 | } catch (Exception e) { 98 | e.printStackTrace(); 99 | } 100 | } 101 | 102 | public static boolean setHeader(URLConnection conn, Map header) { 103 | if (conn == null || header == null || header.isEmpty()) { 104 | return false; 105 | } 106 | try { 107 | Set> set = header.entrySet(); 108 | for (Map.Entry me : set) { 109 | conn.setRequestProperty(me.getKey(), me.getValue()); 110 | } 111 | return true; 112 | } catch (Exception e) { 113 | log("/* SET-HEADER EXCEPTION : " + (e != null ? e.getMessage() : "NULL") + " */"); 114 | e.printStackTrace(); 115 | } 116 | return false; 117 | 118 | } 119 | 120 | public static int repeatConnect(URLConnection conn, int retryCount) throws Exception { 121 | if (conn == null) { 122 | return 0; 123 | } 124 | Exception last = null; 125 | /* connect */ 126 | for (int i = 0; i < retryCount; i++) { 127 | try { 128 | conn.connect(); 129 | return i; 130 | } catch (Exception e) { 131 | last = e; 132 | log("/* REPEATLY-CONNECT : " + (i + 1) + " " + (e != null ? e.getMessage() : "NULL") + " */"); 133 | e.printStackTrace(); 134 | snooze(); 135 | } 136 | } 137 | log("ERROR: connect EXCEED max=" + retryCount); 138 | throw last != null ? last : new IllegalAccessException("exceed max retry count " + retryCount); 139 | } 140 | 141 | /* for data */ 142 | 143 | public static void getConnResult(URLConnection conn, OutputStream os, ProgressListener listener, Response response) throws Exception { 144 | final boolean hasOs = os != null; 145 | InputStream is = conn.getInputStream(); 146 | if (!hasOs) { 147 | os = new ByteArrayOutputStream(); 148 | } 149 | write(os, is, listener, conn.getContentLength()); 150 | if (!hasOs) { 151 | response.result = os.toString(); 152 | } 153 | if (conn instanceof HttpURLConnection) { 154 | response.statusCode = ((HttpURLConnection) conn).getResponseCode(); 155 | } 156 | close(is); 157 | } 158 | 159 | public static boolean upload(URLConnection conn, InputStream is, ProgressListener listener) { 160 | if (is == null) { 161 | return false; 162 | } 163 | OutputStream os = null; 164 | try { 165 | if (conn != null) { 166 | os = conn.getOutputStream(); 167 | BufferedOutputStream bos = new BufferedOutputStream(os); 168 | return write(bos, is, listener, -1); 169 | } 170 | } catch (Exception e) { 171 | log("/* UPLOAD EXCEPTION : " + (e != null ? e.getMessage() : "NULL") + " */"); 172 | e.printStackTrace(); 173 | } finally { 174 | close(os); 175 | } 176 | return false; 177 | } 178 | 179 | public static boolean write(final OutputStream os, final InputStream is, final ProgressListener listener, long length) { 180 | if (os == null || is == null) { 181 | return false; 182 | } 183 | try { 184 | // 185 | final long total = is.available(); 186 | final byte[] buffer = new byte[S_BUFF_SIZE]; 187 | // 188 | int len; 189 | long readLen = 0; 190 | while ((len = is.read(buffer)) != -1) { 191 | readLen += len; 192 | os.write(buffer, 0, len); 193 | if (listener != null) { 194 | final long current = readLen; 195 | HANDLER.post(new Runnable() { 196 | @Override 197 | public void run() { 198 | listener.onProgress(os, is, total, current, (total > current) ? (int) (current / total) * 100 : -1); 199 | } 200 | }); 201 | } 202 | } 203 | // 204 | os.flush(); 205 | return true; 206 | } catch (Exception e) { 207 | log("/* WRITE EXCEPTION : " + (e != null ? e.getMessage() : "NULL") + " */"); 208 | } 209 | return false; 210 | } 211 | 212 | /* utilities */ 213 | public static boolean close(Closeable... closeable) { 214 | if (closeable == null || closeable.length == 0) { 215 | return false; 216 | } 217 | for (Closeable cls : closeable) { 218 | if (cls == null) { 219 | continue; 220 | } 221 | try { 222 | cls.close(); 223 | } catch (Exception e) { 224 | } 225 | } 226 | return true; 227 | } 228 | 229 | 230 | public static void log(String log) { 231 | if (!DEBUG) { 232 | return; 233 | } 234 | Log.d(LiteHttp.class.getSimpleName(), log); 235 | } 236 | 237 | public static void snooze() { 238 | try { 239 | Thread.sleep(200); 240 | } catch (Exception e) { 241 | e.printStackTrace(); 242 | } 243 | } 244 | 245 | /* connector */ 246 | public enum Method { 247 | OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE 248 | } 249 | 250 | public static class Response { 251 | public String result; 252 | public int statusCode; 253 | public Exception exception; 254 | 255 | private Response() { 256 | } 257 | } 258 | 259 | public static class Request { 260 | int retry = S_MAX_REPEAT_COUNT; 261 | // 262 | String url; 263 | Method method = Method.GET; 264 | Map header; 265 | StreamListener streamListener; 266 | ProgressListener progressListener; 267 | 268 | public Request setUrl(String url) { 269 | this.url = url; 270 | return this; 271 | } 272 | 273 | public Request setRetry(int retry) { 274 | this.retry = retry; 275 | return this; 276 | } 277 | 278 | /** 279 | * {@link Method#GET} is default 280 | */ 281 | public Request setMethod(Method m) { 282 | this.method = m; 283 | return this; 284 | } 285 | 286 | public Request setHeader(Map h) { 287 | this.header = h; 288 | return this; 289 | } 290 | 291 | public Request setStreamListener(StreamListener streamListener) { 292 | this.streamListener = streamListener; 293 | return this; 294 | } 295 | 296 | public Request setProgressListener(ProgressListener progressListener) { 297 | this.progressListener = progressListener; 298 | return this; 299 | } 300 | 301 | public Request() { 302 | } 303 | 304 | public Response connect() { 305 | Response response = new Response(); 306 | final InputStream is = streamListener != null ? streamListener.getInStream() : null; 307 | final OutputStream os = streamListener != null ? streamListener.getOutStream() : null; 308 | try { 309 | HttpURLConnection conn = beginConnect(method.name().toUpperCase(), url, header, is != null, retry); 310 | if (conn == null) { 311 | return null; 312 | } 313 | if (is != null) { 314 | upload(conn, is, progressListener); 315 | } 316 | try { 317 | getConnResult(conn, os, progressListener, response); 318 | } finally { 319 | conn.disconnect(); 320 | } 321 | } catch (Exception e) { 322 | response.exception = e; 323 | } finally { 324 | close(is, os); 325 | } 326 | return response; 327 | } 328 | } 329 | 330 | public interface StreamListener { 331 | /*for body/upload*/ 332 | InputStream getInStream(); 333 | 334 | /*for download*/ 335 | OutputStream getOutStream(); 336 | } 337 | 338 | public interface ProgressListener { 339 | void onProgress(OutputStream os, InputStream is, long total, long current, int progress); 340 | } 341 | } 342 | 343 | -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 23 5 | buildToolsVersion "24.0.0" 6 | 7 | defaultConfig { 8 | applicationId "me.yourbay.litehttp_sample" 9 | minSdkVersion 14 10 | targetSdkVersion 22 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | // compile project(':liteHttp') 24 | // compile 'me.yourbay.tools:liteHttp:1.0' 25 | compile 'me.yourbay.basic:liteHttp:1.0' 26 | compile 'com.android.support:appcompat-v7:23.2.0' 27 | } 28 | -------------------------------------------------------------------------------- /sample/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 /Users/ram/android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /sample/src/main/java/me/yourbay/litehttp_sample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package me.yourbay.litehttp_sample; 2 | 3 | import android.os.Bundle; 4 | import android.os.Environment; 5 | import android.os.Handler; 6 | import android.os.HandlerThread; 7 | import android.support.v7.app.AppCompatActivity; 8 | import android.text.TextUtils; 9 | import android.view.View; 10 | import android.widget.Button; 11 | import android.widget.TextView; 12 | 13 | import java.io.BufferedOutputStream; 14 | import java.io.File; 15 | import java.io.FileOutputStream; 16 | import java.io.IOException; 17 | import java.io.InputStream; 18 | import java.io.OutputStream; 19 | import java.net.URLEncoder; 20 | 21 | import me.yourbay.litehttp.LiteHttp; 22 | 23 | public class MainActivity extends AppCompatActivity { 24 | 25 | private TextView mTvResult; 26 | private Handler mHandler; 27 | private Button mBtnDown; 28 | 29 | @Override 30 | protected void onCreate(Bundle savedInstanceState) { 31 | super.onCreate(savedInstanceState); 32 | setContentView(R.layout.activity_main); 33 | mTvResult = (TextView) findViewById(R.id.tv_result); 34 | findViewById(R.id.btn_get).setOnClickListener(new View.OnClickListener() { 35 | @Override 36 | public void onClick(View v) { 37 | onGetClick(v); 38 | } 39 | }); 40 | mBtnDown = (Button) findViewById(R.id.btn_download); 41 | mBtnDown.setOnClickListener(new View.OnClickListener() { 42 | @Override 43 | public void onClick(View v) { 44 | onDownClick(v); 45 | } 46 | }); 47 | // 48 | HandlerThread handlerThread = new HandlerThread("HttpRetriever"); 49 | handlerThread.start(); 50 | mHandler = new Handler(handlerThread.getLooper()); 51 | } 52 | 53 | @Override 54 | protected void onDestroy() { 55 | super.onDestroy(); 56 | mHandler.removeCallbacksAndMessages(null); 57 | } 58 | 59 | public void onGetClick(View v) { 60 | run(new Runnable() { 61 | @Override 62 | public void run() { 63 | final String url = "http://api.t.sina.com.cn/short_url/shorten.json?source=2483680040&url_long=" + URLEncoder.encode("http://yourbay.me"); 64 | final String result = new LiteHttp.Request().setUrl(url).connect().result; 65 | showResult(result); 66 | } 67 | }); 68 | } 69 | 70 | public void onDownClick(View v) { 71 | run(new Runnable() { 72 | @Override 73 | public void run() { 74 | final String url = "http://cdn.lamborghini.com/content/models/Huracan_LP_580-2/huracan-lp580-2_hook_1000x1000.jpg"; 75 | final File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "lp580" + System.currentTimeMillis() + ".jpg"); 76 | final String result = 77 | new LiteHttp.Request().setUrl(url)// 78 | .setStreamListener(new LiteHttp.StreamListener() { 79 | @Override 80 | public OutputStream getOutStream() { 81 | try { 82 | file.createNewFile(); 83 | return new BufferedOutputStream(new FileOutputStream(file), 16 * 1024); 84 | } catch (IOException e) { 85 | e.printStackTrace(); 86 | } 87 | return null; 88 | } 89 | 90 | @Override 91 | public InputStream getInStream() { 92 | // if you need to upload file or add body, you can override this 93 | return null; 94 | } 95 | })// 96 | .setProgressListener(new LiteHttp.ProgressListener() { 97 | int lastProgress = -1; 98 | 99 | @Override 100 | public void onProgress(OutputStream os, InputStream is, long total, long current, int progress) { 101 | lastProgress = progress; 102 | mBtnDown.setText("Down" + "(" + current + "B)"); 103 | } 104 | })// 105 | .connect().result; 106 | showResult(file.getAbsolutePath() + "\nDownload " + (file.length() > 0 ? "Succeed" : "Failed") + (TextUtils.isEmpty(result) ? "" : ("\n" + result))); 107 | } 108 | }); 109 | } 110 | 111 | private void showResult(final String result) { 112 | runOnUiThread(new Runnable() { 113 | @Override 114 | public void run() { 115 | final CharSequence preStr = mTvResult.getText(); 116 | mTvResult.setText(result); 117 | mTvResult.append("\n"); 118 | mTvResult.append(preStr); 119 | } 120 | }); 121 | } 122 | 123 | private void run(Runnable runnable) { 124 | mHandler.post(runnable); 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 16 | 17 |