├── .gitignore
├── AsyncOkHttpClient
├── build.gradle
├── gradle.properties
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── library
│ ├── build.gradle
│ ├── gradle.properties
│ └── src
│ │ └── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── com
│ │ └── github
│ │ └── leonardoxh
│ │ └── asyncokhttpclient
│ │ ├── AsyncHttpRequest.java
│ │ ├── AsyncHttpResponse.java
│ │ ├── AsyncOkHttpClient.java
│ │ ├── ByteAsyncHttpResponse.java
│ │ ├── JsonAsyncHttpResponse.java
│ │ ├── RequestModel.java
│ │ ├── RequestParams.java
│ │ └── utils
│ │ ├── RequestMethod.java
│ │ └── Util.java
├── maven_push.gradle
└── settings.gradle
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | # Custom
2 | _site
3 |
4 | # Ant
5 | MANIFEST.MF
6 | ./*.jar
7 | build.num
8 | build
9 |
10 | # ADT
11 | .classpath
12 | .project
13 | .settings
14 | local.properties
15 | bin
16 | gen
17 | _layouts
18 | proguard.cfg
19 |
20 | # OSX
21 | .DS_Store
22 |
23 | # Github
24 | gh-pages
25 |
26 | # Gradle
27 | .gradle
28 | build
29 |
30 | # IDEA
31 | *.iml
32 | *.ipr
33 | *.iws
34 | out
35 | .idea
36 |
37 | # Maven
38 | target
39 | release.properties
40 | pom.xml.*
41 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | buildscript {
3 | repositories {
4 | mavenCentral()
5 | }
6 | dependencies {
7 | classpath 'com.android.tools.build:gradle:0.9.+'
8 | }
9 | }
10 |
11 | allprojects {
12 | repositories {
13 | mavenCentral()
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/gradle.properties:
--------------------------------------------------------------------------------
1 | GROUP=com.github.leonardoxh
2 | VERSION_NAME=1.1
3 | VERSION_CODE=2
4 | POM_DESCRIPTION=Asynchronous client based on Square Inc. OkHttpClient
5 | POM_URL=https://github.com/leonardoxh/AsyncOkHttpClient
6 | POM_SCM_URL=https://github.com/leonardoxh/AsyncOkHttpClient
7 | POM_SCM_CONNECTION=scm:git@github.com:leonardoxh/AsyncOkHttpClient.git
8 | POM_SCM_DEV_CONNECTION=scm:git@github.com:leonardoxh/AsyncOkHttpClient.git
9 | POM_LICENCE_NAME=The Apache Software License, Version 2.0
10 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
11 | POM_LICENCE_DIST=repo
12 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/leonardoxh/AsyncOkHttpClient/1d77fc043404485a256fbb710cc35c4cefa88f05/AsyncOkHttpClient/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/AsyncOkHttpClient/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Wed Apr 10 15:27:10 PDT 2013
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=http\://services.gradle.org/distributions/gradle-1.10-all.zip
7 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/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 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/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 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'android-library'
2 |
3 | dependencies {
4 | compile 'com.squareup.okhttp:okhttp:1.5.4@jar'
5 | }
6 |
7 | android {
8 | compileSdkVersion 19
9 | buildToolsVersion "19.0.3"
10 |
11 | defaultConfig {
12 | minSdkVersion 4
13 | targetSdkVersion 19
14 | }
15 |
16 | buildTypes {
17 | release {
18 | runProguard false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
20 | }
21 | }
22 |
23 | }
24 |
25 | apply from: '../maven_push.gradle'
26 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/library/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_NAME=AsyncOkHttpClient Library
2 | POM_ARTIFACT_ID=AsyncOkHttpClient
3 | POM_PACKAGING=aar
4 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/library/src/main/java/com/github/leonardoxh/asyncokhttpclient/AsyncHttpRequest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2014 Leonardo Rossetto
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.leonardoxh.asyncokhttpclient;
17 |
18 | import com.github.leonardoxh.asyncokhttpclient.utils.RequestMethod;
19 | import com.squareup.okhttp.OkHttpClient;
20 |
21 | import java.io.IOException;
22 | import java.io.OutputStream;
23 | import java.net.HttpURLConnection;
24 | import java.util.Map;
25 |
26 | /**
27 | * Handles the the messages for start/success/error/end of the incomming requests
28 | * @author Leonardo Rossetto
29 | */
30 | public class AsyncHttpRequest implements Runnable {
31 |
32 | /** The callback response */
33 | private final AsyncHttpResponse mResponse;
34 |
35 | /** Client to execute the request */
36 | private final HttpURLConnection mClient;
37 |
38 | /** The request parameters for the request */
39 | private final RequestParams mRequestParams;
40 |
41 | /** The model that contains the request method and request headers */
42 | private final RequestModel mRequest;
43 |
44 | /**
45 | * Constructs a new instance of AsyncHttpRequest
46 | * @param client the client to execute the given request
47 | * @param responseHandler the callback for fire responses like success and error
48 | * @param params the request parameters for GET, POST...
49 | * @param request the model that contains the request method and headers
50 | */
51 | public AsyncHttpRequest(OkHttpClient client, AsyncHttpResponse responseHandler,
52 | RequestParams params, RequestModel request) {
53 | mResponse = responseHandler;
54 | mClient = client.open(request.getURL());
55 | mRequest = request;
56 | mRequestParams = params;
57 | }
58 |
59 | /** Run the current request yaaa! */
60 | @Override
61 | public void run() {
62 | if(mResponse == null) throw new NullPointerException("response can't be null");
63 | try {
64 | mResponse.sendStartMessage();
65 | makeRequest();
66 | mResponse.sendEndMessage();
67 | } catch(IOException e) {
68 | mResponse.sendFailMessage(e, null);
69 | mResponse.sendEndMessage();
70 | } finally {
71 | disconnect();
72 | }
73 | }
74 |
75 | /** Disconnect the current request after send the end message */
76 | protected void disconnect() {
77 | mClient.disconnect();
78 | }
79 |
80 | /**
81 | * Attach the request parameters and headers to request
82 | * and sent it to AsyncHttpResponse to execute them
83 | * @throws IOException If for any reason the RequestParams cannot be write on request body
84 | * @see com.github.leonardoxh.asyncokhttpclient.AsyncHttpResponse
85 | * @see com.github.leonardoxh.asyncokhttpclient.RequestParams
86 | */
87 | private void makeRequest() throws IOException {
88 | try {
89 | if(!Thread.currentThread().isInterrupted()
90 | && mResponse != null) {
91 | mClient.setRequestMethod(mRequest.getRequestMethod());
92 | for(Map.Entry entry : mRequest.getHeaders().entrySet()) {
93 | mClient.setRequestProperty(entry.getKey(), entry.getValue());
94 | }
95 | if(mRequestParams != null &&
96 | !RequestMethod.GET.equals(mRequest.getRequestMethod())) {
97 | OutputStream params = mClient.getOutputStream();
98 | mRequestParams.writeTo(params);
99 | params.close();
100 | }
101 | mResponse.sendResponseMessage(mClient);
102 | }
103 | } catch(IOException e) {
104 | if(!Thread.currentThread().isInterrupted()) throw e;
105 | }
106 | }
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/library/src/main/java/com/github/leonardoxh/asyncokhttpclient/AsyncHttpResponse.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2014 Leonardo Rossetto
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.leonardoxh.asyncokhttpclient;
17 |
18 | import java.io.IOException;
19 | import java.io.InputStream;
20 | import java.net.HttpRetryException;
21 | import java.net.HttpURLConnection;
22 |
23 | import com.github.leonardoxh.asyncokhttpclient.utils.Util;
24 |
25 | import android.os.Handler;
26 | import android.os.Looper;
27 | import android.os.Message;
28 |
29 | /**
30 | * Retrive the response from the HttpURLConnection
31 | * and send it to the relative callback like onSuccess, onError
32 | * @author Leonardo Rossetto
33 | * @see #onSuccess(int, String)
34 | * @see #onError(java.lang.Throwable, java.lang.String)
35 | * @see #onStart()
36 | * @see #onFinish()
37 | */
38 | public class AsyncHttpResponse implements Handler.Callback {
39 |
40 | /** Indicate the response has finished with success */
41 | protected static final int SUCCESS = 0;
42 |
43 | /** Indicate the response has failed */
44 | protected static final int FAIL = 1;
45 |
46 | /** Indicate the response has started */
47 | protected static final int START = 2;
48 |
49 | /** Indicate the response has finished (after onSuccess or onError) */
50 | protected static final int FINISH = 3;
51 |
52 | /** Handler used to pass the messages over the threads */
53 | private Handler mHandler;
54 |
55 | /** Construct a new instance of AsyncHttpResponse */
56 | public AsyncHttpResponse() {
57 | if(Looper.myLooper() != null) mHandler = new Handler(this);
58 | }
59 |
60 | /** Callback that indicate the request has started */
61 | public void onStart() { }
62 |
63 | /** Callback that indicate the request has finished */
64 | public void onFinish() { }
65 |
66 | /**
67 | * Callback that indicate the request has
68 | * this method returns the content of the response
69 | * @param statusCode the request status code normally 200 or 202
70 | * @param content the request response body
71 | */
72 | public void onSuccess(int statusCode, String content) { }
73 |
74 | /**
75 | * Callback that indicate the request has return error
76 | * @param error a Exception class that indicate the error
77 | * @param content the page error content if available or null
78 | * @see java.net.HttpRetryException
79 | */
80 | public void onError(Throwable error, String content) { }
81 |
82 | /**
83 | * Send the success message to the handler
84 | * @param statusCode the success request status code (normally 200 or 202)
85 | * @param responseBody the response body of the request (if any) or null
86 | */
87 | protected void sendSuccessMessage(int statusCode, String responseBody) {
88 | sendMessage(obtainMessage(SUCCESS, new Object[] {Integer.valueOf(statusCode), responseBody}));
89 | }
90 |
91 | /**
92 | * Send the fail message to the handler
93 | * @param error the detail exception error
94 | * @param content the request response body (if any) or null
95 | */
96 | protected void sendFailMessage(Throwable error, String content) {
97 | sendMessage(obtainMessage(FAIL, new Object[] {error, content}));
98 | }
99 |
100 | /**
101 | * Send the handle message that indicate the request has started
102 | */
103 | protected void sendStartMessage() {
104 | sendMessage(obtainMessage(START, null));
105 | }
106 |
107 | /**
108 | * Send the handle message that indicate the request has finished
109 | */
110 | protected void sendEndMessage() {
111 | sendMessage(obtainMessage(FINISH, null));
112 | }
113 |
114 | /**
115 | * Handle the success message and call the relative callback
116 | * @param statusCode the request response status code
117 | * @param responseBody the request response body (if any) or null
118 | * @see #onSuccess(int, java.lang.String)
119 | */
120 | protected void handleSuccessMessage(int statusCode, String responseBody) {
121 | onSuccess(statusCode, responseBody);
122 | }
123 |
124 | /**
125 | * Handle the fail message and call the relative callback
126 | * @param error the detail exception
127 | * @param responseBody the response body of the request (if any) or null
128 | * @see #onError(java.lang.Throwable, java.lang.String)
129 | */
130 | protected void handleFailMessage(Throwable error, String responseBody) {
131 | onError(error, responseBody);
132 | }
133 |
134 | @Override
135 | public boolean handleMessage(Message message) {
136 | switch(message.what) {
137 | case START:
138 | onStart();
139 | return true;
140 | case FINISH:
141 | onFinish();
142 | return true;
143 | case SUCCESS:
144 | Object[] successResponse = (Object[])message.obj;
145 | handleSuccessMessage(((Integer)successResponse[0]).intValue(), (String)successResponse[1]);
146 | return true;
147 | case FAIL:
148 | Object[] failResponse = (Object[])message.obj;
149 | handleFailMessage((Throwable)failResponse[0], (String)failResponse[1]);
150 | return true;
151 | }
152 | return false;
153 | }
154 |
155 | /**
156 | * Send a message over the handler,
157 | * if the handler is null no problems it will recreate it
158 | * @param message the message for send, can't be null
159 | */
160 | protected void sendMessage(Message message) {
161 | if(mHandler != null) {
162 | mHandler.sendMessage(message);
163 | } else {
164 | handleMessage(message);
165 | }
166 | }
167 |
168 | /**
169 | * Obtain a handler thread message to verify the results
170 | * this method will always return a valid message
171 | * @param responseMessage the response message identifier
172 | * @param response the response object to describle this message
173 | * @return a valid thread message based on the given parameters
174 | */
175 | protected Message obtainMessage(int responseMessage, Object response) {
176 | Message message = null;
177 | if(mHandler != null) {
178 | message = mHandler.obtainMessage(responseMessage, response);
179 | } else {
180 | message = Message.obtain();
181 | message.what = responseMessage;
182 | message.obj = response;
183 | }
184 | return message;
185 | }
186 |
187 | /**
188 | * Perform the connection with the given client
189 | * and return the response to the relative callback
190 | * @param connection the connection to execute and collect the informations
191 | */
192 | void sendResponseMessage(HttpURLConnection connection) {
193 | String responseBody = null;
194 | InputStream response = null;
195 | try {
196 | int responseCode = connection.getResponseCode();
197 | if(responseCode >= 300) {
198 | response = connection.getErrorStream();
199 | if(response != null) responseBody = Util.inputStreamToString(response);
200 | sendFailMessage(new HttpRetryException(connection.getResponseMessage(),
201 | responseCode), responseBody);
202 | } else {
203 | response = connection.getInputStream();
204 | if(response != null) responseBody = Util.inputStreamToString(response);
205 | sendSuccessMessage(responseCode, responseBody);
206 | }
207 | } catch(IOException e) {
208 | sendFailMessage(e, (String)null);
209 | } finally {
210 | if(response != null) Util.closeQuietly(response);
211 | }
212 | }
213 |
214 | }
215 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/library/src/main/java/com/github/leonardoxh/asyncokhttpclient/AsyncOkHttpClient.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2014 Leonardo Rossetto
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.leonardoxh.asyncokhttpclient;
17 |
18 | import java.net.MalformedURLException;
19 | import java.net.URL;
20 | import java.util.concurrent.Executors;
21 | import java.util.concurrent.ThreadPoolExecutor;
22 | import java.util.concurrent.TimeUnit;
23 |
24 | import com.github.leonardoxh.asyncokhttpclient.utils.RequestMethod;
25 | import com.github.leonardoxh.asyncokhttpclient.utils.Util;
26 | import com.squareup.okhttp.OkHttpClient;
27 |
28 | /**
29 | * Main class should be used to controll all the client
30 | * @author Leonardo Rossetto
31 | */
32 | public class AsyncOkHttpClient {
33 |
34 | /** The default read time out in seconds */
35 | private static final long DEFAULT_READ_TIMEOUT = 20;
36 |
37 | /** The default connect timeout in seconds */
38 | private static final long DEFAULT_CONNECT_TIMEOUT = 15;
39 |
40 | /** The executor that will execute the request on a separated thread*/
41 | private ThreadPoolExecutor mThreadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
42 |
43 | /** The request model for internal usage will make the headers more easy to set */
44 | private final RequestModel mRequest = new RequestModel();
45 |
46 | /** The main actor of this library tanks to Square Inc. */
47 | private final OkHttpClient mClient = new OkHttpClient();
48 |
49 | public AsyncOkHttpClient() {
50 | mClient.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS);
51 | mClient.setReadTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS);
52 | }
53 |
54 | /**
55 | * Return a instance used for the requests on this client
56 | * @return a valid instance of the OkHttp used for the requests on this client
57 | * @see com.squareup.okhttp.OkHttpClient
58 | */
59 | public OkHttpClient getOkHttpClient() {
60 | return mClient;
61 | }
62 |
63 | /**
64 | * Add a header on the request,
65 | * please note a null header key of a null header value
66 | * will quietly be ignored from the final headers
67 | * ensure that passe parameter is not null
68 | * @param key the header name
69 | * @param value the header value
70 | */
71 | public void addHeader(String key, String value) {
72 | mRequest.addHeader(key, value);
73 | }
74 |
75 | /**
76 | * Set the executor to execute the requests
77 | * on the most use cases this is not necessary
78 | * but is a good choice for make unit tests
79 | * @param threadPool a new thread pool for execute the incoming requests
80 | */
81 | public void setThreadPool(ThreadPoolExecutor threadPool) {
82 | mThreadPool = threadPool;
83 | }
84 |
85 | /**
86 | * Set the connection timeout for the requests based on the time unit
87 | * 0 means no timeout
88 | * @param timeout a new timeout value
89 | * @param unit the unit for the timeout
90 | * @see java.util.concurrent.TimeUnit
91 | */
92 | public void setConnectionTimeut(long timeout, TimeUnit unit) {
93 | mClient.setConnectTimeout(timeout, unit);
94 | }
95 |
96 | /**
97 | * Set the read timeout for the requests based on the time unit
98 | * 0 means no timeout
99 | * @param timeout a new timeout value
100 | * @param unit the unit for the timeout
101 | * @see java.util.concurrent.TimeUnit
102 | */
103 | public void setReadTieout(long timeout, TimeUnit unit) {
104 | mClient.setReadTimeout(timeout, unit);
105 | }
106 |
107 | /**
108 | * Send the specific request for the request response
109 | * @param client the client for execute the request
110 | * @param url the url for execute
111 | * @param response the response handler for this request
112 | * @param params the request parameters null parameters means no parameters
113 | * @param requestMethod the request method for requests
114 | * @see com.github.leonardoxh.asyncokhttpclient.AsyncHttpRequest
115 | * @see com.github.leonardoxh.asyncokhttpclient.utils.RequestMethod
116 | */
117 | protected void sendRequest(OkHttpClient client, String url, AsyncHttpResponse response,
118 | RequestParams params, String requestMethod) {
119 | try {
120 | mRequest.setRequestMethod(requestMethod);
121 | mRequest.setUrl(new URL(url));
122 | mThreadPool.submit(new AsyncHttpRequest(client, response, params, mRequest));
123 | } catch(MalformedURLException e) {
124 | e.printStackTrace(); //TODO
125 | }
126 | }
127 |
128 | /**
129 | * Execute a GET request
130 | * @param url the url for execute
131 | * @param response the response handler to manage the results
132 | */
133 | public void get(String url, AsyncHttpResponse response) {
134 | get(url, null, response);
135 | }
136 |
137 | /**
138 | * Execute a GET request
139 | * @param url the url for execute
140 | * @param params the request parameters null parameters means no parameters
141 | * @param response the response handler to manage the results
142 | */
143 | public void get(String url, RequestParams params, AsyncHttpResponse response) {
144 | sendRequest(mClient, Util.getUrlWithQueryString(url, params),
145 | response, params, RequestMethod.GET);
146 | }
147 |
148 | /**
149 | * Execute a POST request
150 | * @param url the url for execute
151 | * @param response the response handler to manage the results
152 | */
153 | public void post(String url, AsyncHttpResponse response) {
154 | post(url, null, response);
155 | }
156 |
157 | /**
158 | * Execute a POST request
159 | * @param url the url for execute
160 | * @param params the request parameters null parameters means no parameters
161 | * @param response the response handler to manage the results
162 | */
163 | public void post(String url, RequestParams params, AsyncHttpResponse response) {
164 | sendRequest(mClient, url, response, params,
165 | RequestMethod.POST);
166 | }
167 |
168 | /**
169 | * Execute a PUT request
170 | * @param url the url for execute
171 | * @param params the request parameters null parameters means no parameters
172 | * @param response the response handler to manage the results
173 | */
174 | public void put(String url, RequestParams params, AsyncHttpResponse response) {
175 | sendRequest(mClient, url, response, params,
176 | RequestMethod.PUT);
177 | }
178 |
179 | /**
180 | * Execute a PUT request
181 | * @param url the url for execute
182 | * @param response the response handler to manage the results
183 | */
184 | public void put(String url, AsyncHttpResponse response) {
185 | put(url, null, response);
186 | }
187 |
188 | /**
189 | * Execute a DELETE request
190 | * @param url the url for execute
191 | * @param params the request parameters null parameters means no parameters
192 | * @param response the response handler to manage the results
193 | */
194 | public void delete(String url, RequestParams params, AsyncHttpResponse response) {
195 | sendRequest(mClient, url, response, params,
196 | RequestMethod.DELETE);
197 | }
198 |
199 | /**
200 | * Execute a DELETE request
201 | * @param url the url for execute
202 | * @param response the response handler to manage the results
203 | */
204 | public void delete(String url, AsyncHttpResponse response) {
205 | delete(url, null, response);
206 | }
207 |
208 | }
--------------------------------------------------------------------------------
/AsyncOkHttpClient/library/src/main/java/com/github/leonardoxh/asyncokhttpclient/ByteAsyncHttpResponse.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Leonardo Rossetto
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.leonardoxh.asyncokhttpclient;
17 |
18 | import java.io.IOException;
19 | import java.io.InputStream;
20 | import java.net.HttpRetryException;
21 | import java.net.HttpURLConnection;
22 |
23 | import com.github.leonardoxh.asyncokhttpclient.utils.Util;
24 |
25 | import android.os.Message;
26 |
27 | /**
28 | * Handle the HttpURLConnection response
29 | * and parse it on a valid byte[] response
30 | * @author Leonardo Rossetto
31 | * @see #onSuccess(int, byte[])
32 | * @see #onError(java.lang.Throwable, byte[])
33 | */
34 | public class ByteAsyncHttpResponse extends AsyncHttpResponse {
35 |
36 | /** Indicate the response as a valid byte array message */
37 | protected static final int SUCCESS_BYTE_ARRAY = 7;
38 |
39 | /** Indicate the response as a fail byte array message */
40 | protected static final int FAIL_BYTE_ARRAY = 8;
41 |
42 | /**
43 | * Callback that indicate the response as finished with success
44 | * @param statusCode the status code of this request
45 | * @param content the content of this request
46 | */
47 | public void onSuccess(int statusCode, byte[] content) { }
48 |
49 | /**
50 | * Callback that indicate the response as finished with a fail
51 | * but have a valid byte array response
52 | * @param error the stack trace of the error message
53 | * @param content the content of this request
54 | */
55 | public void onError(Throwable error, byte[] content) { }
56 |
57 | /**
58 | * Send a success byte array message to handler
59 | * @param statusCode the status code of the request
60 | * @param responseBody the response body of the request or null
61 | */
62 | protected void sendSuccessMessage(int statusCode, byte[] responseBody) {
63 | sendMessage(obtainMessage(SUCCESS_BYTE_ARRAY, new Object[] {statusCode, responseBody}));
64 | }
65 |
66 | /**
67 | * Send a fail message to the handler
68 | * @param error the related stack trace of the request
69 | * @param responseBody the response body of the request or null
70 | */
71 | protected void sendFailMessage(Throwable error, byte[] responseBody) {
72 | sendMessage(obtainMessage(FAIL_BYTE_ARRAY, new Object[] {error, responseBody}));
73 | }
74 |
75 | /**
76 | * Handle the success message and call the callback
77 | * @param statusCode the status code of the request
78 | * @param responseBody the response body or null
79 | * @see #onSuccess(int, byte[])
80 | */
81 | protected void handleSuccessByteArrayMessage(int statusCode, byte[] responseBody) {
82 | onSuccess(statusCode, responseBody);
83 | }
84 |
85 | /**
86 | * Handle the error message and call the callback
87 | * @param error the stack trace of this response
88 | * @param responseBody the response body of this request or null
89 | * @see #onError(java.lang.Throwable, byte[])
90 | */
91 | protected void handleFailByteArrayMessage(Throwable error, byte[] responseBody) {
92 | onError(error, responseBody);
93 | }
94 |
95 | @Override
96 | public boolean handleMessage(Message message) {
97 | switch(message.what) {
98 | case SUCCESS_BYTE_ARRAY:
99 | Object[] successResponse = (Object[])message.obj;
100 | handleSuccessByteArrayMessage(((Integer)successResponse[0]).intValue(),
101 | (byte[])successResponse[1]);
102 | return true;
103 | case FAIL_BYTE_ARRAY:
104 | Object[] failResponse = (Object[])message.obj;
105 | handleFailByteArrayMessage((Throwable)failResponse[0], (byte[])failResponse[1]);
106 | return true;
107 | default:
108 | return super.handleMessage(message);
109 | }
110 | }
111 |
112 | @Override
113 | void sendResponseMessage(HttpURLConnection connection) {
114 | InputStream response = null;
115 | byte[] responseBody = null;
116 | try {
117 | int statusCode = connection.getResponseCode();
118 | if(statusCode >= 300) {
119 | response = connection.getErrorStream();
120 | if(response != null) responseBody = Util.inputStreamToByteArray(response);
121 | sendFailMessage(new HttpRetryException(connection.getResponseMessage(), statusCode),
122 | responseBody);
123 | } else {
124 | response = connection.getInputStream();
125 | if(response != null) responseBody = Util.inputStreamToByteArray(response);
126 | sendSuccessMessage(statusCode, responseBody);
127 | }
128 | } catch(IOException e) {
129 | sendFailMessage(e, (byte[])null);
130 | } finally {
131 | if(response != null) Util.closeQuietly(response);
132 | }
133 | }
134 |
135 | }
136 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/library/src/main/java/com/github/leonardoxh/asyncokhttpclient/JsonAsyncHttpResponse.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2014 Leonardo Rossetto
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.leonardoxh.asyncokhttpclient;
17 |
18 | import org.json.JSONArray;
19 | import org.json.JSONException;
20 | import org.json.JSONObject;
21 | import org.json.JSONTokener;
22 |
23 | import android.os.Message;
24 |
25 | /**
26 | * This handles retrieve a message from
27 | * the HttpURLConnection and parse it in a JSON
28 | * @author Leonardo Rossetto
29 | * @see #onSuccess(int, org.json.JSONArray)
30 | * @see #onSuccess(int, org.json.JSONObject)
31 | * @see #onError(java.lang.Throwable, org.json.JSONArray)
32 | * @see #onError(java.lang.Throwable, org.json.JSONObject)
33 | * @see #onError(java.lang.Throwable, java.lang.String)
34 | */
35 | public class JsonAsyncHttpResponse extends AsyncHttpResponse {
36 |
37 | /** Indicate the response has a valid JSON and a success message */
38 | protected static final int SUCCESS_JSON = 5;
39 |
40 | /** Indicate the response as a valid JSON and a fail message */
41 | protected static final int FAIL_JSON = 6;
42 |
43 | /**
44 | * Callback that indicate request has finished success
45 | * and its a JSONObject
46 | * @param statusCode the status code of the request normally 200
47 | * @param response the JSON response of this request
48 | */
49 | public void onSuccess(int statusCode, JSONObject response) { }
50 |
51 | /**
52 | * Callback that indicate request has finished success
53 | * and its a JSONArray
54 | * @param statusCode the status code of the request normally 200
55 | * @param response the JSON response of this request
56 | */
57 | public void onSuccess(int statusCode, JSONArray response) { }
58 |
59 | /**
60 | * Callback that indicate request has finished with a fail response
61 | * but a valid JSON body, this is util when you have a server that return a
62 | * valid JSON with the fail detail on the body but the response code >= 300
63 | * @param error the error stack trace of this response
64 | * @param response the response of this request
65 | * @see #onError(java.lang.Throwable, java.lang.String)
66 | */
67 | public void onError(Throwable error, JSONArray response) { }
68 |
69 | /**
70 | * Callback that indicate request has finished with a fail response
71 | * but a valid JSON body, this is util when you have a server that return a
72 | * valid JSON with the fail detail on the body but the response code >= 300
73 | * @param error the error stack trace of this response
74 | * @param response the response of this request
75 | * @see #onError(java.lang.Throwable, java.lang.String)
76 | */
77 | public void onError(Throwable error, JSONObject response) { }
78 |
79 | @Override
80 | protected void sendSuccessMessage(int statusCode, String responseBody) {
81 | try {
82 | Object jsonResponse = parseResponse(responseBody);
83 | if(jsonResponse == null) {
84 | sendMessage(obtainMessage(FAIL_JSON, new Object[] {
85 | new NullPointerException("Response body is null"), responseBody}));
86 | } else {
87 | sendMessage(obtainMessage(SUCCESS_JSON, new Object[] {statusCode, jsonResponse}));
88 | }
89 | } catch(JSONException e) {
90 | sendMessage(obtainMessage(FAIL_JSON, new Object[] {e, responseBody}));
91 | }
92 | }
93 |
94 | @Override
95 | protected void sendFailMessage(Throwable error, String responseBody) {
96 | try {
97 | Object jsonResponse = parseResponse(responseBody);
98 | if(jsonResponse == null) {
99 | sendMessage(obtainMessage(FAIL_JSON, new Object[] {error, responseBody}));
100 | } else {
101 | sendMessage(obtainMessage(FAIL_JSON, new Object[] {error, jsonResponse}));
102 | }
103 | } catch(JSONException e) {
104 | sendMessage(obtainMessage(FAIL_JSON, new Object[] {e, responseBody}));
105 | }
106 | }
107 |
108 | /**
109 | * Parse the response into a valid JSON
110 | * @param response the response to parse
111 | * @return a JSON parsed and ready to use
112 | * @throws JSONException if the JSON is invalid
113 | */
114 | private static Object parseResponse(String response) throws JSONException {
115 | if(response == null) return null;
116 | response = response.trim();
117 | if(response.startsWith("{") || response.startsWith("[")) {
118 | return new JSONTokener(response).nextValue();
119 | }
120 | return null;
121 | }
122 |
123 | @Override
124 | public boolean handleMessage(Message message) {
125 | switch(message.what) {
126 | case SUCCESS_JSON:
127 | Object[] successResponse = (Object[]) message.obj;
128 | handleSuccessJsonMessage(((Integer)successResponse[0]).intValue(), successResponse[1]);
129 | return true;
130 | case FAIL_JSON:
131 | Object[] failResponse = (Object[]) message.obj;
132 | handleErrorJsonMessage((Throwable)failResponse[0], failResponse[1]);
133 | return true;
134 | default:
135 | return super.handleMessage(message);
136 | }
137 | }
138 |
139 | /**
140 | * Handle the error json message and call the onError callback
141 | * @param error the stack trace of error message
142 | * @param jsonResponse the json response to retrieve the instance
143 | * @see #onError(java.lang.Throwable, org.json.JSONArray)
144 | * @see #onError(java.lang.Throwable, org.json.JSONObject)
145 | */
146 | protected void handleErrorJsonMessage(Throwable error, Object jsonResponse) {
147 | if(jsonResponse instanceof JSONObject) {
148 | onError(error, (JSONObject)jsonResponse);
149 | } else if(jsonResponse instanceof JSONArray) {
150 | onError(error, (JSONArray)jsonResponse);
151 | } else if(jsonResponse == null) {
152 | onError(new JSONException("Null response "+error.getLocalizedMessage()), (String)null);
153 | } else {
154 | onError(new JSONException("Unexpected type " + jsonResponse.getClass().getName()), (String)null);
155 | }
156 | }
157 |
158 | /**
159 | * Handle the success json message and call the onSuccess callback or the onError
160 | * @param stautsCode the message status code of this request
161 | * @param jsonResponse the response parsed ready to get instances
162 | * @see #onSuccess(int, org.json.JSONObject)
163 | * @see #onSuccess(int, org.json.JSONArray)
164 | * @see #onError(java.lang.Throwable, java.lang.String)
165 | */
166 | protected void handleSuccessJsonMessage(int stautusCode, Object jsonResponse) {
167 | if(jsonResponse instanceof JSONObject) {
168 | onSuccess(stautusCode, (JSONObject)jsonResponse);
169 | } else if(jsonResponse instanceof JSONArray) {
170 | onSuccess(stautusCode, (JSONArray) jsonResponse);
171 | } else if(jsonResponse == null) {
172 | onError(new JSONException("Null response"), (String)null);
173 | } else {
174 | onError(new JSONException("Unexpected type " + jsonResponse.getClass().getName()), (String) null);
175 | }
176 | }
177 |
178 | }
179 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/library/src/main/java/com/github/leonardoxh/asyncokhttpclient/RequestModel.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2014 Leonardo Rossetto
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.leonardoxh.asyncokhttpclient;
17 |
18 | import com.github.leonardoxh.asyncokhttpclient.utils.RequestMethod;
19 |
20 | import java.net.URL;
21 | import java.util.HashMap;
22 | import java.util.Map;
23 |
24 | /**
25 | * Class to represent a single request (internal API)
26 | * this class holds the request method, headers and URL
27 | * @author Leonardo Rossetto
28 | */
29 | class RequestModel {
30 |
31 | /** The request method, GET by default */
32 | private String mRequestMethod = RequestMethod.GET;
33 |
34 | /** Array that represent the connection headers */
35 | private final Map mHeaders = new HashMap();
36 |
37 | /** The request URL */
38 | private URL mUrl;
39 |
40 | /**
41 | * Construct a new instance of RequestModel
42 | * @param url the url to use on this request
43 | */
44 | public RequestModel(URL url) {
45 | mUrl = url;
46 | }
47 |
48 | /** Construct a new instance of RequestModel */
49 | public RequestModel() { }
50 |
51 | /**
52 | * Set the URL for this request
53 | * @param url a new valid url for this request
54 | */
55 | public void setUrl(URL url) {
56 | mUrl = url;
57 | }
58 |
59 | /**
60 | * @return a url of this request
61 | */
62 | public URL getURL() {
63 | return mUrl;
64 | }
65 |
66 | /**
67 | * Set a new request method of this request
68 | * @param requestMethod the new request method for this request
69 | * @see com.github.leonardoxh.asyncokhttpclient.utils.RequestMethod
70 | */
71 | public void setRequestMethod(String requestMethod) {
72 | mRequestMethod = requestMethod;
73 | }
74 |
75 | /**
76 | * Add a header for this request
77 | * @param key the header name
78 | * @param value the header value
79 | */
80 | public void addHeader(String key, String value) {
81 | mHeaders.put(key, value);
82 | }
83 |
84 | /**
85 | * Add multiple headers to this request
86 | * @param headers a map that contain all headers on this request, can't be null
87 | */
88 | public void addHeaders(Map headers) {
89 | mHeaders.putAll(headers);
90 | }
91 |
92 | /** Clear the associated headers of this request */
93 | public void clearHeaders() {
94 | mHeaders.clear();
95 | }
96 |
97 | /**
98 | * @return The headers of this request
99 | */
100 | public Map getHeaders() {
101 | return mHeaders;
102 | }
103 |
104 | /**
105 | * @return The request method of this request
106 | */
107 | public String getRequestMethod() {
108 | return mRequestMethod;
109 | }
110 |
111 | }
112 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/library/src/main/java/com/github/leonardoxh/asyncokhttpclient/RequestParams.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2014 Leonardo Rossetto
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.leonardoxh.asyncokhttpclient;
17 |
18 | import java.io.IOException;
19 | import java.io.OutputStream;
20 | import java.util.Map;
21 | import java.util.concurrent.ConcurrentHashMap;
22 |
23 | /**
24 | * Representation class for request parameters
25 | * @author Leonardo Rossetto
26 | * @see com.github.leonardoxh.asyncokhttpclient.utils.RequestMethod
27 | */
28 | public class RequestParams {
29 |
30 | /** This is the headers */
31 | private final Map mParams = new ConcurrentHashMap();
32 |
33 | /**
34 | * Put multiple parameters on this parameters
35 | * @param source the mapa with the parameters of this request
36 | * note a null parameter here will thrown a NullPointerException
37 | */
38 | public void put(Map source) {
39 | for(Map.Entry entry : source.entrySet()) {
40 | put(entry.getKey(), entry.getValue());
41 | }
42 | }
43 |
44 | /**
45 | * Put the parameter on this params
46 | * note if the parameter name is null or
47 | * parameter value is null it will be siently omited from this parameters
48 | * @param key the parameter name
49 | * @param value the parameter value
50 | */
51 | public void put(String key, String value) {
52 | if(key != null && value != null) {
53 | mParams.put(key, value);
54 | }
55 | }
56 |
57 | /** Clear the parameter map */
58 | public void clear() {
59 | mParams.clear();
60 | }
61 |
62 | /**
63 | * Return the encoded parameter of this request
64 | * ready for HttpURLConnection set on OutputStream
65 | * @return the parameters encoded
66 | */
67 | public String getParams() {
68 | StringBuilder result = new StringBuilder();
69 | for(ConcurrentHashMap.Entry entry : mParams.entrySet()) {
70 | if(result.length() > 0) result.append("&");
71 | result.append(entry.getKey());
72 | result.append("=");
73 | result.append(entry.getValue());
74 | }
75 | return result.toString();
76 | }
77 |
78 | public void writeTo(OutputStream output) throws IOException {
79 | output.write(getParams().getBytes());
80 | }
81 |
82 | @Override
83 | /**
84 | * The encoded parameters of this request
85 | * @return the encoded parameters of this request
86 | * @see #getParams()
87 | */
88 | public String toString() {
89 | return getParams();
90 | }
91 |
92 | }
93 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/library/src/main/java/com/github/leonardoxh/asyncokhttpclient/utils/RequestMethod.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2014 Leonardo Rossetto
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.leonardoxh.asyncokhttpclient.utils;
17 |
18 | /**
19 | * Class that hold the supported request methods on this library
20 | * on the most use cases to be used with {@code com.opens.asyncokhttpclient.RequestModel}
21 | * @author Leonardo Rossetto
22 | * @see com.github.leonardoxh.asyncokhttpclient.RequestModel
23 | */
24 | public final class RequestMethod {
25 |
26 | /** No instances */
27 | private RequestMethod() { }
28 |
29 | public static final String GET = "GET";
30 |
31 | public static final String POST = "POST";
32 |
33 | public static final String PUT = "PUT";
34 |
35 | public static final String DELETE = "DELETE";
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/library/src/main/java/com/github/leonardoxh/asyncokhttpclient/utils/Util.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2013-2014 Leonardo Rossetto
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.github.leonardoxh.asyncokhttpclient.utils;
17 |
18 | import java.io.BufferedReader;
19 | import java.io.ByteArrayOutputStream;
20 | import java.io.Closeable;
21 | import java.io.IOException;
22 | import java.io.InputStream;
23 | import java.io.InputStreamReader;
24 |
25 | import com.github.leonardoxh.asyncokhttpclient.RequestParams;
26 |
27 | /**
28 | * Utilitaries class, contains the common methods used
29 | * to decode responses and another utils methods
30 | * @author Leonardo Rossetto
31 | */
32 | public final class Util {
33 |
34 | /** Mark the end of file */
35 | private static final int EOF = -1;
36 |
37 | /** The default buffer size for decodes */
38 | private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
39 |
40 | /** No instances */
41 | private Util() { }
42 |
43 | /**
44 | * Convert the given InputStream to a String
45 | * @param source the InputStream to convert
46 | * @return the String converted based on given InputStream
47 | * @throws IOException If the given InputStream is null or can't be accessed
48 | */
49 | public static String inputStreamToString(InputStream source) throws IOException {
50 | BufferedReader reader = new BufferedReader(new InputStreamReader(source));
51 | StringBuilder out = new StringBuilder();
52 | String line;
53 | while((line = reader.readLine()) != null) {
54 | out.append(line);
55 | }
56 | return out.toString();
57 | }
58 |
59 | /**
60 | * Util for GET request method, convert the given RequestParams
61 | * into a valid URL String query
62 | * @param url the base URL to concat the query
63 | * @param requestParams the query parameters
64 | * @return a valid String URL query for GET methods
65 | * @see com.github.leonardoxh.asyncokhttpclient.utils.RequestMethod
66 | * @see com.github.leonardoxh.asyncokhttpclient.RequestParams
67 | */
68 | public static String getUrlWithQueryString(String url, RequestParams requestParams) {
69 | if(requestParams != null) {
70 | String paramUrl = requestParams.toString();
71 | if(url.indexOf('?') == -1) {
72 | url += "?"+paramUrl;
73 | } else {
74 | url += "&"+paramUrl;
75 | }
76 | }
77 | return url;
78 | }
79 |
80 | /**
81 | * Convert the given InputStream into a byte array
82 | * this class is based o Apache IOUtils common so it can read
83 | * more than 2GB with 4MB buffers
84 | * @param source the InputStream to consume
85 | * @return the byte array decoded
86 | * @throws IOException if the given InputStream can't be decoded
87 | */
88 | public static byte[] inputStreamToByteArray(InputStream source) throws IOException {
89 | ByteArrayOutputStream output = new ByteArrayOutputStream();
90 | byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
91 | int n = 0;
92 | while((n = source.read(buffer)) != EOF) {
93 | output.write(buffer, 0, n);
94 | }
95 | return output.toByteArray();
96 | }
97 |
98 | /**
99 | * Close any Closeable quietly if any exception
100 | * is thrown simple ignore it
101 | * @param closeable a class that implements Closeable to close
102 | */
103 | public static void closeQuietly(Closeable closeable) {
104 | try {
105 | closeable.close();
106 | } catch(IOException ignored) { }
107 | }
108 |
109 | }
110 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/maven_push.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'maven'
2 | apply plugin: 'signing'
3 |
4 | def isReleaseBuild() {
5 | return VERSION_NAME.contains("SNAPSHOT") == false
6 | }
7 |
8 | def getRepositoryUrl() {
9 | if(isReleaseBuild()) {
10 | println 'RELEASE BUILD'
11 | return "https://oss.sonatype.org/service/local/staging/deploy/maven2/"
12 | } else {
13 | println 'DEBUG BUILD'
14 | return "https://oss.sonatype.org/content/repositories/snapshots/"
15 | }
16 | }
17 |
18 | def getRepositoryUsername() {
19 | return hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : ""
20 | }
21 |
22 | def getRepositoryPassword() {
23 | return hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : ""
24 | }
25 |
26 | afterEvaluate { project ->
27 | uploadArchives {
28 | repositories {
29 | mavenDeployer {
30 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
31 |
32 | pom.groupId = GROUP
33 | pom.artifactId = POM_ARTIFACT_ID
34 | pom.version = VERSION_NAME
35 |
36 | repository(url: getRepositoryUrl()) {
37 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
38 | }
39 |
40 | pom.project {
41 | name POM_NAME
42 | packaging POM_PACKAGING
43 | description POM_DESCRIPTION
44 | url POM_URL
45 |
46 | scm {
47 | url POM_SCM_URL
48 | connection POM_SCM_CONNECTION
49 | developerConnection POM_SCM_DEV_CONNECTION
50 | }
51 |
52 | licenses {
53 | license {
54 | name POM_LICENCE_NAME
55 | url POM_LICENCE_URL
56 | distribution POM_LICENCE_DIST
57 | }
58 | }
59 |
60 | developers {
61 | developer {
62 | id "leorossetto"
63 | name "Leonardo Rossetto"
64 | }
65 | }
66 | }
67 | }
68 | }
69 | }
70 |
71 | signing {
72 | required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") }
73 | sign configurations.archives
74 | }
75 |
76 | task androidJavadocs(type: Javadoc) {
77 | source = android.sourceSets.main.allJava
78 | }
79 |
80 | task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
81 | classifier = 'javadoc'
82 | from androidJavadocs.destinationDir
83 | }
84 |
85 | task androidSourcesJar(type: Jar) {
86 | classifier = 'sources'
87 | from android.sourceSets.main.allSource
88 | }
89 |
90 | artifacts {
91 | archives androidSourcesJar
92 | archives androidJavadocsJar
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/AsyncOkHttpClient/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':library'
2 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | For 1.2:
2 | ---
3 | - Cookies persistence support
4 | - Authentication
5 | - Proxy
6 | - Cancel requests (Wooooha)
7 | - Request cache using OkResponseCache from OkHttp
8 | - Bump OkHttp dependency to latest version
9 | - Unit tests using Mockito, Robolectric and MockWebServer (not sure on 1.2 or 1.3)
10 |
11 | 1.1:
12 | ---
13 | - Removed methods that support Content-Type directly, since the Content-Type is a normal header and it can be set by AsyncOkHttpClient.addHeader(java.lang.String, java.lang.String)
14 | is the case of get, post, put and delete overloads.
15 | - Added a JSON fail callbacks with a json response, since a valid json can become on request with a status code >= 303,
16 | all this json is parsed outside UIThread and received on UIThread.
17 | - Added a ByteAsyncHttpResponse, its very power full, can download imagens or bytes from a server very very fast.
18 | - Bug fixes
19 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | Pull Requests
2 | =================
3 | Well if you is seeing this and wanna contribute is a good point, all pull request are welcome but before submit any pull request please review your code and test it, all pull requests will be tested by me, and think in a real use case for the pull request, I **will not** merge a pull request without a motive.
4 |
5 | But if this ok I have some roles and you need follow them, basically is the Android team code style with some adaptations is really easy, this is necessary, like beer:
6 |
7 | 1. Line tab identation is 4 spaces
8 | 2. Line continuation is 8 spaces
9 | 3. Prefrer the foreach
statment before normal for
10 | 4. if
is best then try... catch
11 |
12 | If statments:
13 | ---
14 | **Correct**
15 | ```
16 | if(1 == 1) {
17 | //multiple line if statment
18 | }
19 |
20 | if(1 == 1) System.out.println("This if is ok");
21 | ```
22 | **Incorrect**
23 | ```
24 | if(1 == 1)
25 | System.out.println("oh s**it");
26 | ```
27 |
28 | And this is so important to, avoid put a blank lines on your code example:
29 | **correct**
30 | ```
31 | void method() {
32 | System.out.println("OK");
33 | System.out.println("Another line goes here");
34 | }
35 | ```
36 | **Incorrect**
37 | ```
38 | void method() {
39 | System.out.println("This...");
40 |
41 | System.out.println("IS NOT CORRECT HERE");
42 | }
43 | ```
44 | Methods must be separated by 1 blank line its easy:
45 | ```
46 | void method() {
47 | //code...
48 | }
49 |
50 | void method2() {
51 | //code...
52 | }
53 | ```
54 | Methods without code, this way:
55 | ```
56 | void method() { }
57 | ```
58 | Variable cast:
59 | ```
60 | String a = (String)obj;
61 | ```
62 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction, and
10 | distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright
13 | owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all other entities
16 | that control, are controlled by, or are under common control with that entity.
17 | For the purposes of this definition, "control" means (i) the power, direct or
18 | indirect, to cause the direction or management of such entity, whether by
19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20 | outstanding shares, or (iii) beneficial ownership of such entity.
21 |
22 | "You" (or "Your") shall mean an individual or Legal Entity exercising
23 | permissions granted by this License.
24 |
25 | "Source" form shall mean the preferred form for making modifications, including
26 | but not limited to software source code, documentation source, and configuration
27 | files.
28 |
29 | "Object" form shall mean any form resulting from mechanical transformation or
30 | translation of a Source form, including but not limited to compiled object code,
31 | generated documentation, and conversions to other media types.
32 |
33 | "Work" shall mean the work of authorship, whether in Source or Object form, made
34 | available under the License, as indicated by a copyright notice that is included
35 | in or attached to the work (an example is provided in the Appendix below).
36 |
37 | "Derivative Works" shall mean any work, whether in Source or Object form, that
38 | is based on (or derived from) the Work and for which the editorial revisions,
39 | annotations, elaborations, or other modifications represent, as a whole, an
40 | original work of authorship. For the purposes of this License, Derivative Works
41 | shall not include works that remain separable from, or merely link (or bind by
42 | name) to the interfaces of, the Work and Derivative Works thereof.
43 |
44 | "Contribution" shall mean any work of authorship, including the original version
45 | of the Work and any modifications or additions to that Work or Derivative Works
46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work
47 | by the copyright owner or by an individual or Legal Entity authorized to submit
48 | on behalf of the copyright owner. For the purposes of this definition,
49 | "submitted" means any form of electronic, verbal, or written communication sent
50 | to the Licensor or its representatives, including but not limited to
51 | communication on electronic mailing lists, source code control systems, and
52 | issue tracking systems that are managed by, or on behalf of, the Licensor for
53 | the purpose of discussing and improving the Work, but excluding communication
54 | that is conspicuously marked or otherwise designated in writing by the copyright
55 | owner as "Not a Contribution."
56 |
57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58 | of whom a Contribution has been received by Licensor and subsequently
59 | incorporated within the Work.
60 |
61 | 2. Grant of Copyright License.
62 |
63 | Subject to the terms and conditions of this License, each Contributor hereby
64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
65 | irrevocable copyright license to reproduce, prepare Derivative Works of,
66 | publicly display, publicly perform, sublicense, and distribute the Work and such
67 | Derivative Works in Source or Object form.
68 |
69 | 3. Grant of Patent License.
70 |
71 | Subject to the terms and conditions of this License, each Contributor hereby
72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
73 | irrevocable (except as stated in this section) patent license to make, have
74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where
75 | such license applies only to those patent claims licensable by such Contributor
76 | that are necessarily infringed by their Contribution(s) alone or by combination
77 | of their Contribution(s) with the Work to which such Contribution(s) was
78 | submitted. If You institute patent litigation against any entity (including a
79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a
80 | Contribution incorporated within the Work constitutes direct or contributory
81 | patent infringement, then any patent licenses granted to You under this License
82 | for that Work shall terminate as of the date such litigation is filed.
83 |
84 | 4. Redistribution.
85 |
86 | You may reproduce and distribute copies of the Work or Derivative Works thereof
87 | in any medium, with or without modifications, and in Source or Object form,
88 | provided that You meet the following conditions:
89 |
90 | You must give any other recipients of the Work or Derivative Works a copy of
91 | this License; and
92 | You must cause any modified files to carry prominent notices stating that You
93 | changed the files; and
94 | You must retain, in the Source form of any Derivative Works that You distribute,
95 | all copyright, patent, trademark, and attribution notices from the Source form
96 | of the Work, excluding those notices that do not pertain to any part of the
97 | Derivative Works; and
98 | If the Work includes a "NOTICE" text file as part of its distribution, then any
99 | Derivative Works that You distribute must include a readable copy of the
100 | attribution notices contained within such NOTICE file, excluding those notices
101 | that do not pertain to any part of the Derivative Works, in at least one of the
102 | following places: within a NOTICE text file distributed as part of the
103 | Derivative Works; within the Source form or documentation, if provided along
104 | with the Derivative Works; or, within a display generated by the Derivative
105 | Works, if and wherever such third-party notices normally appear. The contents of
106 | the NOTICE file are for informational purposes only and do not modify the
107 | License. You may add Your own attribution notices within Derivative Works that
108 | You distribute, alongside or as an addendum to the NOTICE text from the Work,
109 | provided that such additional attribution notices cannot be construed as
110 | modifying the License.
111 | You may add Your own copyright statement to Your modifications and may provide
112 | additional or different license terms and conditions for use, reproduction, or
113 | distribution of Your modifications, or for any such Derivative Works as a whole,
114 | provided Your use, reproduction, and distribution of the Work otherwise complies
115 | with the conditions stated in this License.
116 |
117 | 5. Submission of Contributions.
118 |
119 | Unless You explicitly state otherwise, any Contribution intentionally submitted
120 | for inclusion in the Work by You to the Licensor shall be under the terms and
121 | conditions of this License, without any additional terms or conditions.
122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of
123 | any separate license agreement you may have executed with Licensor regarding
124 | such Contributions.
125 |
126 | 6. Trademarks.
127 |
128 | This License does not grant permission to use the trade names, trademarks,
129 | service marks, or product names of the Licensor, except as required for
130 | reasonable and customary use in describing the origin of the Work and
131 | reproducing the content of the NOTICE file.
132 |
133 | 7. Disclaimer of Warranty.
134 |
135 | Unless required by applicable law or agreed to in writing, Licensor provides the
136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
138 | including, without limitation, any warranties or conditions of TITLE,
139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
140 | solely responsible for determining the appropriateness of using or
141 | redistributing the Work and assume any risks associated with Your exercise of
142 | permissions under this License.
143 |
144 | 8. Limitation of Liability.
145 |
146 | In no event and under no legal theory, whether in tort (including negligence),
147 | contract, or otherwise, unless required by applicable law (such as deliberate
148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be
149 | liable to You for damages, including any direct, indirect, special, incidental,
150 | or consequential damages of any character arising as a result of this License or
151 | out of the use or inability to use the Work (including but not limited to
152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or
153 | any and all other commercial damages or losses), even if such Contributor has
154 | been advised of the possibility of such damages.
155 |
156 | 9. Accepting Warranty or Additional Liability.
157 |
158 | While redistributing the Work or Derivative Works thereof, You may choose to
159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or
160 | other liability obligations and/or rights consistent with this License. However,
161 | in accepting such obligations, You may act only on Your own behalf and on Your
162 | sole responsibility, not on behalf of any other Contributor, and only if You
163 | agree to indemnify, defend, and hold each Contributor harmless for any liability
164 | incurred by, or claims asserted against, such Contributor by reason of your
165 | accepting any such warranty or additional liability.
166 |
167 | END OF TERMS AND CONDITIONS
168 |
169 | APPENDIX: How to apply the Apache License to your work
170 |
171 | To apply the Apache License to your work, attach the following boilerplate
172 | notice, with the fields enclosed by brackets "[]" replaced with your own
173 | identifying information. (Don't include the brackets!) The text should be
174 | enclosed in the appropriate comment syntax for the file format. We also
175 | recommend that a file or class name and description of purpose be included on
176 | the same "printed page" as the copyright notice for easier identification within
177 | third-party archives.
178 |
179 | Copyright [yyyy] [name of copyright owner]
180 |
181 | Licensed under the Apache License, Version 2.0 (the "License");
182 | you may not use this file except in compliance with the License.
183 | You may obtain a copy of the License at
184 |
185 | http://www.apache.org/licenses/LICENSE-2.0
186 |
187 | Unless required by applicable law or agreed to in writing, software
188 | distributed under the License is distributed on an "AS IS" BASIS,
189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190 | See the License for the specific language governing permissions and
191 | limitations under the License.
192 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | AsyncOkHttpClient Http Client for Android
2 | =================
3 |
4 | This is a asynchronous library based on James Smith [Android Async Http Library](https://github.com/loopj/android-async-http).
5 |
6 | Instead use Apache http librarys this library use the Square Inc. [OkHttpClient](https://github.com/square/okhttp), so its mutch more fast and can be used on Android 2.2 and above.
7 |
8 | Important Note:
9 | --------
10 | Now the OkHttpClient have their own async API, which means this library will no be longer maintained.
11 | I think the Square OkHttpClient async API is more effetive in allways, and have a better support for Async calls and features, no other layer on top of it is required, so...
12 | I will release on next weeks a final version of this library, but I strongly recommend use the OkHttp async layer instead of this.
13 | --------
14 |
15 | Features
16 | --------
17 | - Make **asynchronous** HTTP requests, handle responses in **anonymous callbacks**
18 | - HTTP requests happen **outside the UI thread**
19 | - Requests use a **threadpool** to cap concurrent resource usage
20 | - GET/POST/PUT **params builder** (RequestParams)
21 |
22 | Example:
23 | --------
24 | ```
25 | AsyncOkHttpClient client = new AsyncOkHttpClient();
26 | client.get("http://www.google.com", new AsyncHttpResponse() {
27 |
28 | @Override
29 | public void onStart() {
30 | System.out.println("onStart is called on UIThread");
31 | }
32 |
33 | @Override
34 | public void onFinish() {
35 | System.out.println("onFinish");
36 | }
37 |
38 | @Override
39 | public void onSuccess(int statusCode, String content) {
40 | System.out.println("CONTENT: " + content);
41 | }
42 |
43 | @Override
44 | public void onError(Throwable error, String content) {
45 | //Error called check the Throwable instance
46 | if(error instanceof HttpRetryException) {
47 | //Get the error code
48 | HttpRetryException detailError = (HttpRetryException) error;
49 | System.out.println("Response Code: " + detailError.responseCode());
50 | } else {
51 | //Another error cause like permission not declared on AndroidManifest or time out exception
52 | }
53 | }
54 |
55 | });
56 | ```
57 |
58 |
59 | Gradle:
60 | =================
61 | ```
62 | Latest stable version is: 1.1 and snapshot is 1.1-SNAPSHOT
63 | ```
64 |
65 | ```
66 | dependencies {
67 | compile 'com.github.leonardoxh:AsyncOkHttpClient:1.1@aar'
68 | }
69 | ```
70 |
71 | Changelog:
72 | =================
73 | ```
74 | Read the Changelog.md
75 | ```
76 |
77 | Contributing:
78 | =================
79 | ```
80 | All pull request are wellcome, but first think in a real use case for the
81 | pull request, this library **will not** support lots of features.
82 | Before submit any change please read the CONTRIBUTING.md
83 | ```
84 |
85 | Licence:
86 | =================
87 | ```
88 | Copyright 2013-2014 Leonardo Rossetto
89 |
90 | Licensed under the Apache License, Version 2.0 (the "License");
91 | you may not use this file except in compliance with the License.
92 | You may obtain a copy of the License at
93 |
94 | http://www.apache.org/licenses/LICENSE-2.0
95 |
96 | Unless required by applicable law or agreed to in writing, software
97 | distributed under the License is distributed on an "AS IS" BASIS,
98 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
99 | See the License for the specific language governing permissions and
100 | limitations under the License.
101 | ```
102 |
--------------------------------------------------------------------------------