├── app ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── colors.xml │ │ │ │ ├── dimens.xml │ │ │ │ └── styles.xml │ │ │ ├── mipmap-hdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-mdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── values-w820dp │ │ │ │ └── dimens.xml │ │ │ └── layout │ │ │ │ └── activity_main.xml │ │ ├── java │ │ │ └── com │ │ │ │ └── tsy12321 │ │ │ │ └── netdemo │ │ │ │ ├── http │ │ │ │ ├── lib │ │ │ │ │ ├── LibVolleyResponseModel.java │ │ │ │ │ ├── LibVolley.java │ │ │ │ │ ├── LibOkHttp.java │ │ │ │ │ ├── LibAsyncHttp.java │ │ │ │ │ └── LibVolleyJsonObjectRequest.java │ │ │ │ ├── MyHttpJsonResponseHandler.java │ │ │ │ ├── MyHttpFileResponseHandler.java │ │ │ │ ├── MyHttp.java │ │ │ │ └── glue │ │ │ │ │ ├── MyVolley.java │ │ │ │ │ ├── MyOkHttp.java │ │ │ │ │ └── MyAsyncHttp.java │ │ │ │ ├── GlobalApp.java │ │ │ │ ├── SharedPreferenceUtils.java │ │ │ │ └── MainActivity.java │ │ └── AndroidManifest.xml │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── tsy12321 │ │ │ └── netdemo │ │ │ └── ExampleUnitTest.java │ └── androidTest │ │ └── java │ │ └── com │ │ └── tsy12321 │ │ └── netdemo │ │ └── ApplicationTest.java ├── proguard-rules.pro └── build.gradle ├── settings.gradle ├── volley-android-6.0.1_25 ├── rules.gradle ├── .gitignore ├── src │ └── main │ │ ├── AndroidManifest.xml │ │ └── java │ │ └── com │ │ └── android │ │ └── volley │ │ ├── TimeoutError.java │ │ ├── ServerError.java │ │ ├── NoConnectionError.java │ │ ├── ParseError.java │ │ ├── Network.java │ │ ├── NetworkError.java │ │ ├── toolbox │ │ ├── Authenticator.java │ │ ├── NoCache.java │ │ ├── HttpStack.java │ │ ├── ClearCacheRequest.java │ │ ├── StringRequest.java │ │ ├── JsonArrayRequest.java │ │ ├── Volley.java │ │ ├── JsonObjectRequest.java │ │ ├── PoolingByteArrayOutputStream.java │ │ ├── JsonRequest.java │ │ ├── AndroidAuthenticator.java │ │ ├── RequestFuture.java │ │ ├── ByteArrayPool.java │ │ ├── HttpHeaderParser.java │ │ ├── HttpClientStack.java │ │ ├── NetworkImageView.java │ │ ├── HurlStack.java │ │ └── ImageRequest.java │ │ ├── ResponseDelivery.java │ │ ├── RetryPolicy.java │ │ ├── VolleyError.java │ │ ├── AuthFailureError.java │ │ ├── NetworkResponse.java │ │ ├── Response.java │ │ ├── Cache.java │ │ ├── DefaultRetryPolicy.java │ │ ├── ExecutorDelivery.java │ │ ├── NetworkDispatcher.java │ │ ├── CacheDispatcher.java │ │ └── VolleyLog.java ├── custom_rules.xml ├── build.gradle ├── proguard-project.txt ├── Android.mk ├── proguard.cfg ├── build.xml └── pom.xml ├── .gitignore ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew.bat ├── gradlew └── README.md /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':volley-android-6.0.1_25' 2 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/rules.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | NetDemo 3 | 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsy12321/Android-Http-Example/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /volley-android-6.0.1_25/.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | gen 3 | .gradle 4 | build 5 | .settings 6 | target 7 | *.iml 8 | .idea 9 | local.properties 10 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsy12321/Android-Http-Example/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsy12321/Android-Http-Example/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsy12321/Android-Http-Example/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsy12321/Android-Http-Example/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsy12321/Android-Http-Example/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/custom_rules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /app/src/test/java/com/tsy12321/netdemo/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * To work on unit tests, switch the Test Artifact in the Build Variants view. 9 | */ 10 | public class ExampleUnitTest { 11 | @Test 12 | public void addition_isCorrect() throws Exception { 13 | assertEquals(4, 2 + 2); 14 | } 15 | } -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/tsy12321/netdemo/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/main/java/com/tsy12321/netdemo/http/lib/LibVolleyResponseModel.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo.http.lib; 2 | 3 | import org.json.JSONObject; 4 | 5 | import java.util.Map; 6 | 7 | /** 8 | * volley response数据模型 9 | * Created by tsy on 16/5/23. 10 | */ 11 | public class LibVolleyResponseModel { 12 | public Map headers; //response头 13 | public int status; //response status 14 | public JSONObject data; //response 数据 15 | } 16 | -------------------------------------------------------------------------------- /app/src/main/java/com/tsy12321/netdemo/GlobalApp.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | 6 | /** 7 | * 全局 application 8 | * Created by tsy on 16/5/19. 9 | */ 10 | public class GlobalApp extends Application { 11 | 12 | private static GlobalApp app; 13 | private Context context; 14 | 15 | @Override 16 | public void onCreate() { 17 | super.onCreate(); 18 | 19 | app = this; 20 | context = getApplicationContext(); 21 | } 22 | 23 | public static synchronized GlobalApp getInstance() { 24 | return app; 25 | } 26 | 27 | public Context getContext() { 28 | return context; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/tsy/Library/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 | -------------------------------------------------------------------------------- /app/src/main/java/com/tsy12321/netdemo/http/MyHttpJsonResponseHandler.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo.http; 2 | 3 | import org.json.JSONObject; 4 | 5 | /** 6 | * MyHttpResponse回调 Json数据 7 | * Created by tsy on 16/5/17. 8 | */ 9 | public abstract class MyHttpJsonResponseHandler { 10 | 11 | /** 12 | * 成功返回 13 | * @param statusCode 14 | * @param response 15 | */ 16 | public abstract void onSuccess(int statusCode, JSONObject response); 17 | 18 | /** 19 | * 失败返回 20 | * @param statusCode 21 | * @param error_msg 22 | */ 23 | public abstract void onFailure(int statusCode, String error_msg); 24 | 25 | /** 26 | * 请求被取消 27 | */ 28 | public void onCancel() { 29 | //Log.v("myhttp", "request on cancel"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/build.gradle: -------------------------------------------------------------------------------- 1 | // NOTE: The only changes that belong in this file are the definitions 2 | // of tool versions (gradle plugin, compile SDK, build tools), so that 3 | // Volley can be built via gradle as a standalone project. 4 | // 5 | // Any other changes to the build config belong in rules.gradle, which 6 | // is used by projects that depend on Volley but define their own 7 | // tools versions across all dependencies to ensure a consistent build. 8 | 9 | buildscript { 10 | repositories { 11 | mavenCentral() 12 | } 13 | dependencies { 14 | classpath 'com.android.tools.build:gradle:2.1.2' 15 | } 16 | } 17 | 18 | apply plugin: 'com.android.library' 19 | 20 | android { 21 | compileSdkVersion 19 22 | buildToolsVersion = '23.0.2' 23 | } 24 | 25 | apply from: 'rules.gradle' 26 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 17 | 18 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | ## Project-wide Gradle settings. 2 | # 3 | # For more details on how to configure your build environment visit 4 | # http://www.gradle.org/docs/current/userguide/build_environment.html 5 | # 6 | # Specifies the JVM arguments used for the daemon process. 7 | # The setting is particularly useful for tweaking memory settings. 8 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 9 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 10 | # 11 | # When configured, Gradle will run in incubating parallel mode. 12 | # This option should only be used with decoupled projects. More details, visit 13 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 14 | # org.gradle.parallel=true 15 | #Tue May 17 10:14:26 CST 2016 16 | systemProp.http.proxyHost=127.0.0.1 17 | systemProp.http.proxyPort=1080 18 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/proguard-project.txt: -------------------------------------------------------------------------------- 1 | # To enable ProGuard in your project, edit project.properties 2 | # to define the proguard.config property as described in that file. 3 | # 4 | # Add project specific ProGuard rules here. 5 | # By default, the flags in this file are appended to flags specified 6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt 7 | # You can edit the include path and order by changing the ProGuard 8 | # include property in project.properties. 9 | # 10 | # For more details, see 11 | # http://developer.android.com/guide/developing/tools/proguard.html 12 | 13 | # Add any project specific keep options here: 14 | 15 | # If your project uses WebView with JS, uncomment the following 16 | # and specify the fully qualified class name to the JavaScript interface 17 | # class: 18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 19 | # public *; 20 | #} 21 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 23 5 | buildToolsVersion "23.0.2" 6 | 7 | defaultConfig { 8 | applicationId "com.tsy12321.netdemo" 9 | minSdkVersion 9 10 | targetSdkVersion 23 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 fileTree(include: ['*.jar'], dir: 'libs') 24 | testCompile 'junit:junit:4.12' 25 | compile 'com.android.support:appcompat-v7:23.2.1' 26 | compile 'com.loopj.android:android-async-http:1.4.9' 27 | compile project(':volley-android-6.0.1_25') 28 | compile 'com.squareup.okhttp3:okhttp:3.2.0' 29 | } 30 | -------------------------------------------------------------------------------- /app/src/main/java/com/tsy12321/netdemo/http/MyHttpFileResponseHandler.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo.http; 2 | 3 | import android.util.Log; 4 | 5 | /** 6 | * 文件下载responseHandler 7 | * Created by tsy on 16/5/18. 8 | */ 9 | public abstract class MyHttpFileResponseHandler { 10 | /** 11 | * 成功返回 12 | * @param statusCode 13 | */ 14 | public abstract void onSuccess(int statusCode); 15 | 16 | /** 17 | * 失败返回 18 | * @param statusCode 19 | * @param error_msg 20 | */ 21 | public abstract void onFailure(int statusCode, String error_msg); 22 | 23 | /** 24 | * 下载进度 25 | * @param bytesWritten 已经长传字节 26 | * @param totalSize 总字节 27 | */ 28 | public abstract void onProgress(long bytesWritten, long totalSize); 29 | 30 | /** 31 | * 请求被取消 32 | */ 33 | public void onCancel() { 34 | Log.v("myhttp", "request on cancel"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/TimeoutError.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | /** 20 | * Indicates that the connection or the socket timed out. 21 | */ 22 | @SuppressWarnings("serial") 23 | public class TimeoutError extends VolleyError { } 24 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/ServerError.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | /** 20 | * Indicates that the server responded with an error response. 21 | */ 22 | @SuppressWarnings("serial") 23 | public class ServerError extends VolleyError { 24 | public ServerError(NetworkResponse networkResponse) { 25 | super(networkResponse); 26 | } 27 | 28 | public ServerError() { 29 | super(); 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/NoConnectionError.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | /** 20 | * Error indicating that no connection could be established when performing a Volley request. 21 | */ 22 | @SuppressWarnings("serial") 23 | public class NoConnectionError extends NetworkError { 24 | public NoConnectionError() { 25 | super(); 26 | } 27 | 28 | public NoConnectionError(Throwable reason) { 29 | super(reason); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/ParseError.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | /** 20 | * Indicates that the server's response could not be parsed. 21 | */ 22 | @SuppressWarnings("serial") 23 | public class ParseError extends VolleyError { 24 | public ParseError() { } 25 | 26 | public ParseError(NetworkResponse networkResponse) { 27 | super(networkResponse); 28 | } 29 | 30 | public ParseError(Throwable cause) { 31 | super(cause); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/Android.mk: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (C) 2011 The Android Open Source Project 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | 17 | LOCAL_PATH := $(call my-dir) 18 | 19 | include $(CLEAR_VARS) 20 | 21 | LOCAL_MODULE := volley 22 | LOCAL_SDK_VERSION := 17 23 | LOCAL_SRC_FILES := $(call all-java-files-under, src/main/java) 24 | 25 | include $(BUILD_STATIC_JAVA_LIBRARY) 26 | 27 | # Include this library in the build server's output directory 28 | # TODO: Not yet. 29 | #$(call dist-for-goals, dist_files, $(LOCAL_BUILT_MODULE):volley.jar) 30 | 31 | # Include build files in subdirectories 32 | include $(call all-makefiles-under,$(LOCAL_PATH)) 33 | 34 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/Network.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | /** 20 | * An interface for performing requests. 21 | */ 22 | public interface Network { 23 | /** 24 | * Performs the specified request. 25 | * @param request Request to process 26 | * @return A {@link NetworkResponse} with data and caching metadata; will never be null 27 | * @throws VolleyError on errors 28 | */ 29 | public NetworkResponse performRequest(Request request) throws VolleyError; 30 | } 31 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/NetworkError.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | /** 20 | * Indicates that there was a network error when performing a Volley request. 21 | */ 22 | @SuppressWarnings("serial") 23 | public class NetworkError extends VolleyError { 24 | public NetworkError() { 25 | super(); 26 | } 27 | 28 | public NetworkError(Throwable cause) { 29 | super(cause); 30 | } 31 | 32 | public NetworkError(NetworkResponse networkResponse) { 33 | super(networkResponse); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/Authenticator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import com.android.volley.AuthFailureError; 20 | 21 | /** 22 | * An interface for interacting with auth tokens. 23 | */ 24 | public interface Authenticator { 25 | /** 26 | * Synchronously retrieves an auth token. 27 | * 28 | * @throws AuthFailureError If authentication did not succeed 29 | */ 30 | public String getAuthToken() throws AuthFailureError; 31 | 32 | /** 33 | * Invalidates the provided auth token. 34 | */ 35 | public void invalidateAuthToken(String authToken); 36 | } 37 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/ResponseDelivery.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | public interface ResponseDelivery { 20 | /** 21 | * Parses a response from the network or cache and delivers it. 22 | */ 23 | public void postResponse(Request request, Response response); 24 | 25 | /** 26 | * Parses a response from the network or cache and delivers it. The provided 27 | * Runnable will be executed after delivery. 28 | */ 29 | public void postResponse(Request request, Response response, Runnable runnable); 30 | 31 | /** 32 | * Posts an error for the given request. 33 | */ 34 | public void postError(Request request, VolleyError error); 35 | } 36 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/NoCache.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import com.android.volley.Cache; 20 | 21 | /** 22 | * A cache that doesn't. 23 | */ 24 | public class NoCache implements Cache { 25 | @Override 26 | public void clear() { 27 | } 28 | 29 | @Override 30 | public Entry get(String key) { 31 | return null; 32 | } 33 | 34 | @Override 35 | public void put(String key, Entry entry) { 36 | } 37 | 38 | @Override 39 | public void invalidate(String key, boolean fullExpire) { 40 | } 41 | 42 | @Override 43 | public void remove(String key) { 44 | } 45 | 46 | @Override 47 | public void initialize() { 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/proguard.cfg: -------------------------------------------------------------------------------- 1 | -optimizationpasses 5 2 | -dontusemixedcaseclassnames 3 | -dontskipnonpubliclibraryclasses 4 | -dontpreverify 5 | -verbose 6 | -optimizations !code/simplification/arithmetic,!field/*,!class/merging/* 7 | 8 | -keep public class * extends android.app.Activity 9 | -keep public class * extends android.app.Application 10 | -keep public class * extends android.app.Service 11 | -keep public class * extends android.content.BroadcastReceiver 12 | -keep public class * extends android.content.ContentProvider 13 | -keep public class * extends android.app.backup.BackupAgentHelper 14 | -keep public class * extends android.preference.Preference 15 | -keep public class com.android.vending.licensing.ILicensingService 16 | 17 | -keepclasseswithmembernames class * { 18 | native ; 19 | } 20 | 21 | -keepclasseswithmembers class * { 22 | public (android.content.Context, android.util.AttributeSet); 23 | } 24 | 25 | -keepclasseswithmembers class * { 26 | public (android.content.Context, android.util.AttributeSet, int); 27 | } 28 | 29 | -keepclassmembers class * extends android.app.Activity { 30 | public void *(android.view.View); 31 | } 32 | 33 | -keepclassmembers enum * { 34 | public static **[] values(); 35 | public static ** valueOf(java.lang.String); 36 | } 37 | 38 | -keep class * implements android.os.Parcelable { 39 | public static final android.os.Parcelable$Creator *; 40 | } 41 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/RetryPolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | /** 20 | * Retry policy for a request. 21 | */ 22 | public interface RetryPolicy { 23 | 24 | /** 25 | * Returns the current timeout (used for logging). 26 | */ 27 | public int getCurrentTimeout(); 28 | 29 | /** 30 | * Returns the current retry count (used for logging). 31 | */ 32 | public int getCurrentRetryCount(); 33 | 34 | /** 35 | * Prepares for the next retry by applying a backoff to the timeout. 36 | * @param error The error code of the last attempt. 37 | * @throws VolleyError In the event that the retry could not be performed (for example if we 38 | * ran out of attempts), the passed in error is thrown. 39 | */ 40 | public void retry(VolleyError error) throws VolleyError; 41 | } 42 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/HttpStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import com.android.volley.AuthFailureError; 20 | import com.android.volley.Request; 21 | 22 | import org.apache.http.HttpResponse; 23 | 24 | import java.io.IOException; 25 | import java.util.Map; 26 | 27 | /** 28 | * An HTTP stack abstraction. 29 | */ 30 | public interface HttpStack { 31 | /** 32 | * Performs an HTTP request with the given parameters. 33 | * 34 | *

A GET request is sent if request.getPostBody() == null. A POST request is sent otherwise, 35 | * and the Content-Type header is set to request.getPostBodyContentType().

36 | * 37 | * @param request the request to perform 38 | * @param additionalHeaders additional headers to be sent together with 39 | * {@link Request#getHeaders()} 40 | * @return the HTTP response 41 | */ 42 | public HttpResponse performRequest(Request request, Map additionalHeaders) 43 | throws IOException, AuthFailureError; 44 | 45 | } 46 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/VolleyError.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | /** 20 | * Exception style class encapsulating Volley errors 21 | */ 22 | @SuppressWarnings("serial") 23 | public class VolleyError extends Exception { 24 | public final NetworkResponse networkResponse; 25 | private long networkTimeMs; 26 | 27 | public VolleyError() { 28 | networkResponse = null; 29 | } 30 | 31 | public VolleyError(NetworkResponse response) { 32 | networkResponse = response; 33 | } 34 | 35 | public VolleyError(String exceptionMessage) { 36 | super(exceptionMessage); 37 | networkResponse = null; 38 | } 39 | 40 | public VolleyError(String exceptionMessage, Throwable reason) { 41 | super(exceptionMessage, reason); 42 | networkResponse = null; 43 | } 44 | 45 | public VolleyError(Throwable cause) { 46 | super(cause); 47 | networkResponse = null; 48 | } 49 | 50 | /* package */ void setNetworkTimeMs(long networkTimeMs) { 51 | this.networkTimeMs = networkTimeMs; 52 | } 53 | 54 | public long getNetworkTimeMs() { 55 | return networkTimeMs; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/AuthFailureError.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | import android.content.Intent; 20 | 21 | /** 22 | * Error indicating that there was an authentication failure when performing a Request. 23 | */ 24 | @SuppressWarnings("serial") 25 | public class AuthFailureError extends VolleyError { 26 | /** An intent that can be used to resolve this exception. (Brings up the password dialog.) */ 27 | private Intent mResolutionIntent; 28 | 29 | public AuthFailureError() { } 30 | 31 | public AuthFailureError(Intent intent) { 32 | mResolutionIntent = intent; 33 | } 34 | 35 | public AuthFailureError(NetworkResponse response) { 36 | super(response); 37 | } 38 | 39 | public AuthFailureError(String message) { 40 | super(message); 41 | } 42 | 43 | public AuthFailureError(String message, Exception reason) { 44 | super(message, reason); 45 | } 46 | 47 | public Intent getResolutionIntent() { 48 | return mResolutionIntent; 49 | } 50 | 51 | @Override 52 | public String getMessage() { 53 | if (mResolutionIntent != null) { 54 | return "User needs to (re)enter credentials."; 55 | } 56 | return super.getMessage(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /app/src/main/java/com/tsy12321/netdemo/http/lib/LibVolley.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo.http.lib; 2 | 3 | import android.content.Context; 4 | 5 | import com.android.volley.Request; 6 | import com.android.volley.RequestQueue; 7 | import com.android.volley.Response; 8 | import com.android.volley.toolbox.Volley; 9 | import com.tsy12321.netdemo.GlobalApp; 10 | 11 | import java.util.Map; 12 | 13 | /** 14 | * 对volley的方法封装 15 | * Created by tsy on 16/5/23. 16 | */ 17 | public class LibVolley { 18 | private static RequestQueue mRequestQueue; 19 | 20 | public static void post(Context context, String url, Map headers, Map params, Response.Listener listener, Response.ErrorListener err_listener) { 21 | if(mRequestQueue == null) { 22 | mRequestQueue = Volley.newRequestQueue(GlobalApp.getInstance().getContext()); 23 | } 24 | 25 | LibVolleyJSONObjectRequest request = new LibVolleyJSONObjectRequest(Request.Method.POST, url 26 | , headers, params, listener, err_listener); 27 | 28 | request.setTag(context); 29 | mRequestQueue.add(request); 30 | } 31 | 32 | public static void get(Context context, String url, Map headers, Map params, Response.Listener listener, Response.ErrorListener err_listener) { 33 | if(mRequestQueue == null) { 34 | mRequestQueue = Volley.newRequestQueue(GlobalApp.getInstance().getContext()); 35 | } 36 | 37 | LibVolleyJSONObjectRequest request = new LibVolleyJSONObjectRequest(Request.Method.GET, url 38 | , headers, params, listener, err_listener); 39 | 40 | request.setTag(context); 41 | mRequestQueue.add(request); 42 | } 43 | 44 | /** 45 | * 取消当前context的所有请求 46 | * @param context 当前所在context 47 | */ 48 | public static void cancelRequest(Context context) { 49 | if(mRequestQueue != null && context != null) { 50 | mRequestQueue.cancelAll(context); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /app/src/main/java/com/tsy12321/netdemo/SharedPreferenceUtils.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo; 2 | 3 | import android.content.Context; 4 | import android.content.SharedPreferences; 5 | 6 | /** 7 | * Created by tsy on 16/5/23. 8 | */ 9 | public class SharedPreferenceUtils { 10 | 11 | //本地持久化存储name 12 | private static final String SHARED_PREFERENCES_NAME = "sharedpreference"; 13 | 14 | /** 15 | * 本地持久化存储 16 | * 注:存储可用App本身存储 17 | */ 18 | private static SharedPreferences.Editor mSharePreferenceEditor; 19 | 20 | /** 21 | * 保存数据 22 | * @param context 上下文 23 | * @param name key 24 | * @param data value 25 | */ 26 | public static void saveSharedPreferences(Context context, String name, String data) { 27 | if (mSharePreferenceEditor == null) { 28 | SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); 29 | mSharePreferenceEditor = sharedPreferences.edit(); 30 | } 31 | mSharePreferenceEditor.putString(name, data); 32 | mSharePreferenceEditor.commit(); 33 | } 34 | 35 | /** 36 | * 读取存储数据 37 | * @param context 上下文 38 | * @param name 读取的key 39 | * @return value 40 | */ 41 | public static String readSharedPreferences(Context context, String name) { 42 | SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); 43 | return sharedPreferences.getString(name, ""); 44 | } 45 | 46 | /** 47 | * 移除指定name的信息 48 | * @param context 49 | * @param name 50 | */ 51 | public static void removeSharedPreferences(Context context, String name) { 52 | if (mSharePreferenceEditor == null) { 53 | SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); 54 | mSharePreferenceEditor = sharedPreferences.edit(); 55 | } 56 | mSharePreferenceEditor.remove(name); 57 | mSharePreferenceEditor.commit(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /app/src/main/java/com/tsy12321/netdemo/http/lib/LibOkHttp.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo.http.lib; 2 | 3 | import android.content.Context; 4 | 5 | import java.util.Map; 6 | 7 | import okhttp3.Call; 8 | import okhttp3.Callback; 9 | import okhttp3.FormBody; 10 | import okhttp3.OkHttpClient; 11 | import okhttp3.Request; 12 | 13 | /** 14 | * Created by tsy on 16/5/23. 15 | */ 16 | public class LibOkHttp { 17 | private static OkHttpClient client; 18 | 19 | public static void post(Context context, String url, Map params, Callback callback) { 20 | if(client == null) { 21 | client = new OkHttpClient(); 22 | } 23 | 24 | FormBody.Builder builder = new FormBody.Builder(); 25 | if(params != null && params.size() > 0) { 26 | for (Map.Entry entry : params.entrySet()) { 27 | builder.add(entry.getKey(), entry.getValue()); 28 | } 29 | } 30 | 31 | Request request = new Request.Builder() 32 | .url(url) 33 | .post(builder.build()) 34 | .tag(context) 35 | .build(); 36 | 37 | client.newCall(request).enqueue(callback); 38 | 39 | } 40 | 41 | public static void get(Context context, String url, Callback callback) { 42 | if(client == null) { 43 | client = new OkHttpClient(); 44 | } 45 | 46 | Request request = new Request.Builder() 47 | .url(url) 48 | .tag(context) 49 | .build(); 50 | 51 | client.newCall(request).enqueue(callback); 52 | } 53 | 54 | /** 55 | * 取消当前context的所有请求 56 | * @param context 当前所在context 57 | */ 58 | public static void cancelRequest(Context context) { 59 | if(client != null) { 60 | for(Call call : client.dispatcher().queuedCalls()) { 61 | if(call.request().tag().equals(context)) 62 | call.cancel(); 63 | } 64 | for(Call call : client.dispatcher().runningCalls()) { 65 | if(call.request().tag().equals(context)) 66 | call.cancel(); 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/ClearCacheRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import com.android.volley.Cache; 20 | import com.android.volley.NetworkResponse; 21 | import com.android.volley.Request; 22 | import com.android.volley.Response; 23 | 24 | import android.os.Handler; 25 | import android.os.Looper; 26 | 27 | /** 28 | * A synthetic request used for clearing the cache. 29 | */ 30 | public class ClearCacheRequest extends Request { 31 | private final Cache mCache; 32 | private final Runnable mCallback; 33 | 34 | /** 35 | * Creates a synthetic request for clearing the cache. 36 | * @param cache Cache to clear 37 | * @param callback Callback to make on the main thread once the cache is clear, 38 | * or null for none 39 | */ 40 | public ClearCacheRequest(Cache cache, Runnable callback) { 41 | super(Method.GET, null, null); 42 | mCache = cache; 43 | mCallback = callback; 44 | } 45 | 46 | @Override 47 | public boolean isCanceled() { 48 | // This is a little bit of a hack, but hey, why not. 49 | mCache.clear(); 50 | if (mCallback != null) { 51 | Handler handler = new Handler(Looper.getMainLooper()); 52 | handler.postAtFrontOfQueue(mCallback); 53 | } 54 | return true; 55 | } 56 | 57 | @Override 58 | public Priority getPriority() { 59 | return Priority.IMMEDIATE; 60 | } 61 | 62 | @Override 63 | protected Response parseNetworkResponse(NetworkResponse response) { 64 | return null; 65 | } 66 | 67 | @Override 68 | protected void deliverResponse(Object response) { 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/NetworkResponse.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | import org.apache.http.HttpStatus; 20 | 21 | import java.util.Collections; 22 | import java.util.Map; 23 | 24 | /** 25 | * Data and headers returned from {@link Network#performRequest(Request)}. 26 | */ 27 | public class NetworkResponse { 28 | /** 29 | * Creates a new network response. 30 | * @param statusCode the HTTP status code 31 | * @param data Response body 32 | * @param headers Headers returned with this response, or null for none 33 | * @param notModified True if the server returned a 304 and the data was already in cache 34 | * @param networkTimeMs Round-trip network time to receive network response 35 | */ 36 | public NetworkResponse(int statusCode, byte[] data, Map headers, 37 | boolean notModified, long networkTimeMs) { 38 | this.statusCode = statusCode; 39 | this.data = data; 40 | this.headers = headers; 41 | this.notModified = notModified; 42 | this.networkTimeMs = networkTimeMs; 43 | } 44 | 45 | public NetworkResponse(int statusCode, byte[] data, Map headers, 46 | boolean notModified) { 47 | this(statusCode, data, headers, notModified, 0); 48 | } 49 | 50 | public NetworkResponse(byte[] data) { 51 | this(HttpStatus.SC_OK, data, Collections.emptyMap(), false, 0); 52 | } 53 | 54 | public NetworkResponse(byte[] data, Map headers) { 55 | this(HttpStatus.SC_OK, data, headers, false, 0); 56 | } 57 | 58 | /** The HTTP status code. */ 59 | public final int statusCode; 60 | 61 | /** Raw data from this response. */ 62 | public final byte[] data; 63 | 64 | /** Response headers. */ 65 | public final Map headers; 66 | 67 | /** True if the server returned a 304 (Not Modified). */ 68 | public final boolean notModified; 69 | 70 | /** Network roundtrip time in milliseconds. */ 71 | public final long networkTimeMs; 72 | } 73 | 74 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/StringRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import com.android.volley.NetworkResponse; 20 | import com.android.volley.Request; 21 | import com.android.volley.Response; 22 | import com.android.volley.Response.ErrorListener; 23 | import com.android.volley.Response.Listener; 24 | 25 | import java.io.UnsupportedEncodingException; 26 | 27 | /** 28 | * A canned request for retrieving the response body at a given URL as a String. 29 | */ 30 | public class StringRequest extends Request { 31 | private final Listener mListener; 32 | 33 | /** 34 | * Creates a new request with the given method. 35 | * 36 | * @param method the request {@link Method} to use 37 | * @param url URL to fetch the string at 38 | * @param listener Listener to receive the String response 39 | * @param errorListener Error listener, or null to ignore errors 40 | */ 41 | public StringRequest(int method, String url, Listener listener, 42 | ErrorListener errorListener) { 43 | super(method, url, errorListener); 44 | mListener = listener; 45 | } 46 | 47 | /** 48 | * Creates a new GET request. 49 | * 50 | * @param url URL to fetch the string at 51 | * @param listener Listener to receive the String response 52 | * @param errorListener Error listener, or null to ignore errors 53 | */ 54 | public StringRequest(String url, Listener listener, ErrorListener errorListener) { 55 | this(Method.GET, url, listener, errorListener); 56 | } 57 | 58 | @Override 59 | protected void deliverResponse(String response) { 60 | mListener.onResponse(response); 61 | } 62 | 63 | @Override 64 | protected Response parseNetworkResponse(NetworkResponse response) { 65 | String parsed; 66 | try { 67 | parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); 68 | } catch (UnsupportedEncodingException e) { 69 | parsed = new String(response.data); 70 | } 71 | return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /app/src/main/java/com/tsy12321/netdemo/http/lib/LibAsyncHttp.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo.http.lib; 2 | 3 | import android.content.Context; 4 | import android.content.pm.PackageInfo; 5 | import android.content.pm.PackageManager; 6 | 7 | import com.loopj.android.http.AsyncHttpClient; 8 | import com.loopj.android.http.PersistentCookieStore; 9 | import com.loopj.android.http.RequestParams; 10 | import com.loopj.android.http.ResponseHandlerInterface; 11 | import com.tsy12321.netdemo.GlobalApp; 12 | 13 | /** 14 | * 对AndroidAsyncHttp库的使用封装 15 | * Created by tsy on 16/5/17. 16 | */ 17 | public class LibAsyncHttp { 18 | private static AsyncHttpClient client; 19 | 20 | /** 21 | * post 22 | * @param context 当前所在context 23 | * @param url 24 | * @param params 25 | * @param responseHandler 26 | */ 27 | public static void post(Context context, String url, RequestParams params, ResponseHandlerInterface responseHandler) { 28 | if(client == null) { 29 | client = new AsyncHttpClient(); 30 | client.setUserAgent(getAgaent()); 31 | } 32 | 33 | //cookie功能 34 | PersistentCookieStore cookieStore = new PersistentCookieStore(GlobalApp.getInstance().getContext()); 35 | client.setCookieStore(cookieStore); 36 | 37 | if(context != null) { 38 | client.post(context, url, params, responseHandler); 39 | } else { 40 | client.post(url, params, responseHandler); 41 | } 42 | } 43 | 44 | /** 45 | * get 46 | * @param context 当前所在context 47 | * @param url 48 | * @param params 49 | * @param responseHandler 50 | */ 51 | public static void get(Context context, String url, RequestParams params, ResponseHandlerInterface responseHandler) { 52 | if(client == null) { 53 | client = new AsyncHttpClient(); 54 | client.setUserAgent(getAgaent()); 55 | } 56 | 57 | if(context != null) { 58 | client.get(context, url, params, responseHandler); 59 | } else { 60 | client.get(url, params, responseHandler); 61 | } 62 | } 63 | 64 | /** 65 | * 取消当前context的所有请求 66 | * @param context 当前所在context 67 | */ 68 | public static void cancelRequest(Context context) { 69 | 70 | if(client != null && context != null) { 71 | client.cancelRequests(context, true); 72 | } 73 | } 74 | 75 | private static String getAgaent() { 76 | String userAgent = "androidhttp/0"; 77 | try { 78 | String packageName = GlobalApp.getInstance().getContext().getPackageName(); 79 | PackageInfo info = GlobalApp.getInstance().getContext().getPackageManager().getPackageInfo(packageName, 0); 80 | userAgent = packageName + "/" + info.versionCode; 81 | } catch (PackageManager.NameNotFoundException e) { 82 | } 83 | 84 | return userAgent; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /app/src/main/java/com/tsy12321/netdemo/http/MyHttp.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo.http; 2 | 3 | import android.content.Context; 4 | 5 | import com.tsy12321.netdemo.http.glue.MyAsyncHttp; 6 | import com.tsy12321.netdemo.http.glue.MyOkHttp; 7 | 8 | import java.io.File; 9 | import java.util.Map; 10 | 11 | /** 12 | * 网络请求的统一调用 13 | * 可以修改不同的网络请求库 14 | * Created by tsy on 16/5/17. 15 | */ 16 | public class MyHttp { 17 | 18 | /** 19 | * Post 文本参数 20 | * 回调Json数据 21 | * @param context 当前context 非app context 22 | * @param url 23 | * @param params 24 | * @param responseHandler 25 | */ 26 | public static void doPost(Context context, String url, Mapparams, final MyHttpJsonResponseHandler responseHandler) { 27 | //android-async-http 28 | //MyAsyncHttp.doLibAsyncHttpPost(context, url, params, responseHandler); 29 | 30 | //volley 31 | //MyVolley.doLibVolleyPost(context, url, params, responseHandler); 32 | 33 | //okhttp 34 | MyOkHttp.doLibOkHttpPost(context, url, params, responseHandler); 35 | } 36 | 37 | /** 38 | * Get请求 39 | * @param context 当前context 非app context 40 | * @param url 41 | * @param params 42 | * @param responseHandler 43 | */ 44 | public static void doGet(Context context, String url, Mapparams, final MyHttpJsonResponseHandler responseHandler) { 45 | //android-async-http 46 | //MyAsyncHttp.doLibAsyncHttpGet(context, url, params, responseHandler); 47 | 48 | //volley 49 | //MyVolley.doLibVolleyGet(context, url, params, responseHandler); 50 | 51 | //okhttp 52 | MyOkHttp.doLibOkHttpGet(context, url, params, responseHandler); 53 | } 54 | 55 | /** 56 | * 上传文件 57 | * @param context 当前context 非app context 58 | * @param url 59 | * @param files key-file方式 60 | * @param responseHandler 61 | */ 62 | public static void doUpload(Context context, String url, Mapfiles, final MyHttpFileResponseHandler responseHandler) { 63 | //android-async-http 64 | MyAsyncHttp.doLibAsyncHttpUpload(context, url, files, responseHandler); 65 | } 66 | 67 | /** 68 | * 下载文件 69 | * @param context 当前context 非app context 70 | * @param url 下载地址 71 | * @param target 下载目的file 72 | * @param responseHandler 73 | */ 74 | public static void doDownload(Context context, String url, File target, final MyHttpFileResponseHandler responseHandler) { 75 | //android-async-http 76 | MyAsyncHttp.doLibAsyncHttpDownload(context, url, target, responseHandler); 77 | } 78 | 79 | /** 80 | * 取消当前context的所有请求 81 | * @param context 当前context 非app context 82 | */ 83 | public static void cancelRequest(Context context) { 84 | //android-async-http 85 | MyAsyncHttp.doLibAsyncHttpCacel(context); 86 | 87 | //volley 88 | //MyVolley.doLibVolleyCancel(context); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/Response.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | /** 20 | * Encapsulates a parsed response for delivery. 21 | * 22 | * @param Parsed type of this response 23 | */ 24 | public class Response { 25 | 26 | /** Callback interface for delivering parsed responses. */ 27 | public interface Listener { 28 | /** Called when a response is received. */ 29 | public void onResponse(T response); 30 | } 31 | 32 | /** Callback interface for delivering error responses. */ 33 | public interface ErrorListener { 34 | /** 35 | * Callback method that an error has been occurred with the 36 | * provided error code and optional user-readable message. 37 | */ 38 | public void onErrorResponse(VolleyError error); 39 | } 40 | 41 | /** Returns a successful response containing the parsed result. */ 42 | public static Response success(T result, Cache.Entry cacheEntry) { 43 | return new Response(result, cacheEntry); 44 | } 45 | 46 | /** 47 | * Returns a failed response containing the given error code and an optional 48 | * localized message displayed to the user. 49 | */ 50 | public static Response error(VolleyError error) { 51 | return new Response(error); 52 | } 53 | 54 | /** Parsed response, or null in the case of error. */ 55 | public final T result; 56 | 57 | /** Cache metadata for this response, or null in the case of error. */ 58 | public final Cache.Entry cacheEntry; 59 | 60 | /** Detailed error information if errorCode != OK. */ 61 | public final VolleyError error; 62 | 63 | /** True if this response was a soft-expired one and a second one MAY be coming. */ 64 | public boolean intermediate = false; 65 | 66 | /** 67 | * Returns whether this response is considered successful. 68 | */ 69 | public boolean isSuccess() { 70 | return error == null; 71 | } 72 | 73 | 74 | private Response(T result, Cache.Entry cacheEntry) { 75 | this.result = result; 76 | this.cacheEntry = cacheEntry; 77 | this.error = null; 78 | } 79 | 80 | private Response(VolleyError error) { 81 | this.result = null; 82 | this.cacheEntry = null; 83 | this.error = error; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /app/src/main/java/com/tsy12321/netdemo/http/lib/LibVolleyJsonObjectRequest.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo.http.lib; 2 | 3 | import com.android.volley.AuthFailureError; 4 | import com.android.volley.DefaultRetryPolicy; 5 | import com.android.volley.NetworkResponse; 6 | import com.android.volley.ParseError; 7 | import com.android.volley.Request; 8 | import com.android.volley.Response; 9 | import com.android.volley.toolbox.HttpHeaderParser; 10 | 11 | import org.json.JSONException; 12 | import org.json.JSONObject; 13 | 14 | import java.io.UnsupportedEncodingException; 15 | import java.util.Collections; 16 | import java.util.Map; 17 | import java.util.concurrent.TimeUnit; 18 | 19 | /** 20 | * Created by tsy on 16/5/23. 21 | */ 22 | public class LibVolleyJSONObjectRequest extends Request{ 23 | 24 | private final Response.Listener mListener; 25 | private final Map mHeaders; 26 | private final Map mParams; 27 | 28 | private static final String PROTOCOL_CHARSET = "utf-8"; 29 | 30 | public LibVolleyJSONObjectRequest(int method, String url, Map headers, Map parmas, 31 | Response.Listener listener, Response.ErrorListener errorListener) { 32 | super(method, url, errorListener); 33 | setRetryPolicy(new DefaultRetryPolicy((int) TimeUnit.SECONDS.toMillis(20), DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); 34 | 35 | mListener = listener; 36 | mHeaders = headers; 37 | mParams = parmas; 38 | } 39 | 40 | @Override 41 | protected Map getParams() throws AuthFailureError { 42 | return mParams; 43 | } 44 | 45 | @Override 46 | public Map getHeaders() throws AuthFailureError { 47 | if(mHeaders != null) { 48 | return mHeaders; 49 | } else { 50 | return Collections.emptyMap(); 51 | } 52 | 53 | } 54 | 55 | @Override 56 | protected Response parseNetworkResponse(NetworkResponse response) { 57 | try { 58 | String jsonString = new String(response.data, 59 | HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET)); 60 | 61 | //返回模型 62 | LibVolleyResponseModel my_response = new LibVolleyResponseModel(); 63 | my_response.headers = response.headers; 64 | my_response.status = response.statusCode; 65 | my_response.data = new JSONObject(jsonString); 66 | 67 | return Response.success(my_response, 68 | HttpHeaderParser.parseCacheHeaders(response)); 69 | } catch (UnsupportedEncodingException e) { 70 | return Response.error(new ParseError(e)); 71 | } catch (JSONException je) { 72 | return Response.error(new ParseError(je)); 73 | } 74 | } 75 | 76 | @Override 77 | protected void deliverResponse(LibVolleyResponseModel response) { 78 | mListener.onResponse(response); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /app/src/main/java/com/tsy12321/netdemo/http/glue/MyVolley.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo.http.glue; 2 | 3 | import android.content.Context; 4 | 5 | import com.android.volley.Response; 6 | import com.android.volley.VolleyError; 7 | import com.tsy12321.netdemo.GlobalApp; 8 | import com.tsy12321.netdemo.SharedPreferenceUtils; 9 | import com.tsy12321.netdemo.http.MyHttpJsonResponseHandler; 10 | import com.tsy12321.netdemo.http.lib.LibVolley; 11 | import com.tsy12321.netdemo.http.lib.LibVolleyResponseModel; 12 | 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | /** 17 | * volley调用胶水层 18 | * Created by tsy on 16/5/23. 19 | */ 20 | public class MyVolley { 21 | 22 | /** 23 | * post请求 24 | * @param context 当前上下文 25 | * @param url 26 | * @param params 27 | * @param responseHandler 28 | */ 29 | public static void doLibVolleyPost(Context context, String url, Map params, final MyHttpJsonResponseHandler responseHandler) { 30 | Map headers = new HashMap(); 31 | 32 | //读取cookie放入header 33 | String cookie = SharedPreferenceUtils.readSharedPreferences(GlobalApp.getInstance().getContext(), "cookie"); 34 | headers.put("Cookie", cookie); 35 | 36 | LibVolley.post(context, url, headers, params, new Response.Listener() { 37 | @Override 38 | public void onResponse(LibVolleyResponseModel response) { 39 | //将cookie保存 40 | String cookie = response.headers.get("Set-Cookie"); 41 | SharedPreferenceUtils.saveSharedPreferences(GlobalApp.getInstance().getContext(), "cookie", cookie); 42 | responseHandler.onSuccess(response.status, response.data); 43 | } 44 | }, new Response.ErrorListener() { 45 | @Override 46 | public void onErrorResponse(VolleyError error) { 47 | responseHandler.onFailure(0, error.getMessage()); 48 | } 49 | }); 50 | } 51 | 52 | /** 53 | * get请求 54 | * @param context 当前上下文 55 | * @param url 56 | * @param params 57 | * @param responseHandler 58 | */ 59 | public static void doLibVolleyGet(Context context, String url, Map params, final MyHttpJsonResponseHandler responseHandler) { 60 | Map headers = new HashMap(); 61 | 62 | LibVolley.get(context, url, headers, params, new Response.Listener() { 63 | @Override 64 | public void onResponse(LibVolleyResponseModel response) { 65 | responseHandler.onSuccess(response.status, response.data); 66 | } 67 | }, new Response.ErrorListener() { 68 | @Override 69 | public void onErrorResponse(VolleyError error) { 70 | responseHandler.onFailure(0, error.getMessage()); 71 | } 72 | }); 73 | } 74 | 75 | /** 76 | * 取消请求 77 | * @param context 当前上下文 78 | */ 79 | public static void doLibVolleyCancel(Context context) { 80 | LibVolley.cancelRequest(context); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/JsonArrayRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import com.android.volley.NetworkResponse; 20 | import com.android.volley.ParseError; 21 | import com.android.volley.Response; 22 | import com.android.volley.Response.ErrorListener; 23 | import com.android.volley.Response.Listener; 24 | 25 | import org.json.JSONArray; 26 | import org.json.JSONException; 27 | 28 | import java.io.UnsupportedEncodingException; 29 | 30 | /** 31 | * A request for retrieving a {@link JSONArray} response body at a given URL. 32 | */ 33 | public class JsonArrayRequest extends JsonRequest { 34 | 35 | /** 36 | * Creates a new request. 37 | * @param url URL to fetch the JSON from 38 | * @param listener Listener to receive the JSON response 39 | * @param errorListener Error listener, or null to ignore errors. 40 | */ 41 | public JsonArrayRequest(String url, Listener listener, ErrorListener errorListener) { 42 | super(Method.GET, url, null, listener, errorListener); 43 | } 44 | 45 | /** 46 | * Creates a new request. 47 | * @param method the HTTP method to use 48 | * @param url URL to fetch the JSON from 49 | * @param jsonRequest A {@link JSONArray} to post with the request. Null is allowed and 50 | * indicates no parameters will be posted along with request. 51 | * @param listener Listener to receive the JSON response 52 | * @param errorListener Error listener, or null to ignore errors. 53 | */ 54 | public JsonArrayRequest(int method, String url, JSONArray jsonRequest, 55 | Listener listener, ErrorListener errorListener) { 56 | super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, 57 | errorListener); 58 | } 59 | 60 | @Override 61 | protected Response parseNetworkResponse(NetworkResponse response) { 62 | try { 63 | String jsonString = new String(response.data, 64 | HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET)); 65 | return Response.success(new JSONArray(jsonString), 66 | HttpHeaderParser.parseCacheHeaders(response)); 67 | } catch (UnsupportedEncodingException e) { 68 | return Response.error(new ParseError(e)); 69 | } catch (JSONException je) { 70 | return Response.error(new ParseError(je)); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/Volley.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import android.content.Context; 20 | import android.content.pm.PackageInfo; 21 | import android.content.pm.PackageManager.NameNotFoundException; 22 | import android.net.http.AndroidHttpClient; 23 | import android.os.Build; 24 | 25 | import com.android.volley.Network; 26 | import com.android.volley.RequestQueue; 27 | 28 | import java.io.File; 29 | 30 | public class Volley { 31 | 32 | /** Default on-disk cache directory. */ 33 | private static final String DEFAULT_CACHE_DIR = "volley"; 34 | 35 | /** 36 | * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. 37 | * 38 | * @param context A {@link Context} to use for creating the cache dir. 39 | * @param stack An {@link HttpStack} to use for the network, or null for default. 40 | * @return A started {@link RequestQueue} instance. 41 | */ 42 | public static RequestQueue newRequestQueue(Context context, HttpStack stack) { 43 | File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR); 44 | 45 | String userAgent = "volley/0"; 46 | try { 47 | String packageName = context.getPackageName(); 48 | PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0); 49 | userAgent = packageName + "/" + info.versionCode; 50 | } catch (NameNotFoundException e) { 51 | } 52 | 53 | if (stack == null) { 54 | if (Build.VERSION.SDK_INT >= 9) { 55 | stack = new HurlStack(); 56 | } else { 57 | // Prior to Gingerbread, HttpUrlConnection was unreliable. 58 | // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html 59 | stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent)); 60 | } 61 | } 62 | 63 | Network network = new BasicNetwork(stack); 64 | 65 | RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network); 66 | queue.start(); 67 | 68 | return queue; 69 | } 70 | 71 | /** 72 | * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it. 73 | * 74 | * @param context A {@link Context} to use for creating the cache dir. 75 | * @return A started {@link RequestQueue} instance. 76 | */ 77 | public static RequestQueue newRequestQueue(Context context) { 78 | return newRequestQueue(context, null); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/JsonObjectRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import com.android.volley.NetworkResponse; 20 | import com.android.volley.ParseError; 21 | import com.android.volley.Response; 22 | import com.android.volley.Response.ErrorListener; 23 | import com.android.volley.Response.Listener; 24 | 25 | import org.json.JSONException; 26 | import org.json.JSONObject; 27 | 28 | import java.io.UnsupportedEncodingException; 29 | 30 | /** 31 | * A request for retrieving a {@link JSONObject} response body at a given URL, allowing for an 32 | * optional {@link JSONObject} to be passed in as part of the request body. 33 | */ 34 | public class JsonObjectRequest extends JsonRequest { 35 | 36 | /** 37 | * Creates a new request. 38 | * @param method the HTTP method to use 39 | * @param url URL to fetch the JSON from 40 | * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and 41 | * indicates no parameters will be posted along with request. 42 | * @param listener Listener to receive the JSON response 43 | * @param errorListener Error listener, or null to ignore errors. 44 | */ 45 | public JsonObjectRequest(int method, String url, JSONObject jsonRequest, 46 | Listener listener, ErrorListener errorListener) { 47 | super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, 48 | errorListener); 49 | } 50 | 51 | /** 52 | * Constructor which defaults to GET if jsonRequest is 53 | * null, POST otherwise. 54 | * 55 | * @see #JsonObjectRequest(int, String, JSONObject, Listener, ErrorListener) 56 | */ 57 | public JsonObjectRequest(String url, JSONObject jsonRequest, Listener listener, 58 | ErrorListener errorListener) { 59 | this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest, 60 | listener, errorListener); 61 | } 62 | 63 | @Override 64 | protected Response parseNetworkResponse(NetworkResponse response) { 65 | try { 66 | String jsonString = new String(response.data, 67 | HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET)); 68 | return Response.success(new JSONObject(jsonString), 69 | HttpHeaderParser.parseCacheHeaders(response)); 70 | } catch (UnsupportedEncodingException e) { 71 | return Response.error(new ParseError(e)); 72 | } catch (JSONException je) { 73 | return Response.error(new ParseError(je)); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/PoolingByteArrayOutputStream.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import java.io.ByteArrayOutputStream; 20 | import java.io.IOException; 21 | 22 | /** 23 | * A variation of {@link java.io.ByteArrayOutputStream} that uses a pool of byte[] buffers instead 24 | * of always allocating them fresh, saving on heap churn. 25 | */ 26 | public class PoolingByteArrayOutputStream extends ByteArrayOutputStream { 27 | /** 28 | * If the {@link #PoolingByteArrayOutputStream(ByteArrayPool)} constructor is called, this is 29 | * the default size to which the underlying byte array is initialized. 30 | */ 31 | private static final int DEFAULT_SIZE = 256; 32 | 33 | private final ByteArrayPool mPool; 34 | 35 | /** 36 | * Constructs a new PoolingByteArrayOutputStream with a default size. If more bytes are written 37 | * to this instance, the underlying byte array will expand. 38 | */ 39 | public PoolingByteArrayOutputStream(ByteArrayPool pool) { 40 | this(pool, DEFAULT_SIZE); 41 | } 42 | 43 | /** 44 | * Constructs a new {@code ByteArrayOutputStream} with a default size of {@code size} bytes. If 45 | * more than {@code size} bytes are written to this instance, the underlying byte array will 46 | * expand. 47 | * 48 | * @param size initial size for the underlying byte array. The value will be pinned to a default 49 | * minimum size. 50 | */ 51 | public PoolingByteArrayOutputStream(ByteArrayPool pool, int size) { 52 | mPool = pool; 53 | buf = mPool.getBuf(Math.max(size, DEFAULT_SIZE)); 54 | } 55 | 56 | @Override 57 | public void close() throws IOException { 58 | mPool.returnBuf(buf); 59 | buf = null; 60 | super.close(); 61 | } 62 | 63 | @Override 64 | public void finalize() { 65 | mPool.returnBuf(buf); 66 | } 67 | 68 | /** 69 | * Ensures there is enough space in the buffer for the given number of additional bytes. 70 | */ 71 | private void expand(int i) { 72 | /* Can the buffer handle @i more bytes, if not expand it */ 73 | if (count + i <= buf.length) { 74 | return; 75 | } 76 | byte[] newbuf = mPool.getBuf((count + i) * 2); 77 | System.arraycopy(buf, 0, newbuf, 0, count); 78 | mPool.returnBuf(buf); 79 | buf = newbuf; 80 | } 81 | 82 | @Override 83 | public synchronized void write(byte[] buffer, int offset, int len) { 84 | expand(len); 85 | super.write(buffer, offset, len); 86 | } 87 | 88 | @Override 89 | public synchronized void write(int oneByte) { 90 | expand(1); 91 | super.write(oneByte); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/Cache.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | import java.util.Collections; 20 | import java.util.Map; 21 | 22 | /** 23 | * An interface for a cache keyed by a String with a byte array as data. 24 | */ 25 | public interface Cache { 26 | /** 27 | * Retrieves an entry from the cache. 28 | * @param key Cache key 29 | * @return An {@link Entry} or null in the event of a cache miss 30 | */ 31 | public Entry get(String key); 32 | 33 | /** 34 | * Adds or replaces an entry to the cache. 35 | * @param key Cache key 36 | * @param entry Data to store and metadata for cache coherency, TTL, etc. 37 | */ 38 | public void put(String key, Entry entry); 39 | 40 | /** 41 | * Performs any potentially long-running actions needed to initialize the cache; 42 | * will be called from a worker thread. 43 | */ 44 | public void initialize(); 45 | 46 | /** 47 | * Invalidates an entry in the cache. 48 | * @param key Cache key 49 | * @param fullExpire True to fully expire the entry, false to soft expire 50 | */ 51 | public void invalidate(String key, boolean fullExpire); 52 | 53 | /** 54 | * Removes an entry from the cache. 55 | * @param key Cache key 56 | */ 57 | public void remove(String key); 58 | 59 | /** 60 | * Empties the cache. 61 | */ 62 | public void clear(); 63 | 64 | /** 65 | * Data and metadata for an entry returned by the cache. 66 | */ 67 | public static class Entry { 68 | /** The data returned from cache. */ 69 | public byte[] data; 70 | 71 | /** ETag for cache coherency. */ 72 | public String etag; 73 | 74 | /** Date of this response as reported by the server. */ 75 | public long serverDate; 76 | 77 | /** The last modified date for the requested object. */ 78 | public long lastModified; 79 | 80 | /** TTL for this record. */ 81 | public long ttl; 82 | 83 | /** Soft TTL for this record. */ 84 | public long softTtl; 85 | 86 | /** Immutable response headers as received from server; must be non-null. */ 87 | public Map responseHeaders = Collections.emptyMap(); 88 | 89 | /** True if the entry is expired. */ 90 | public boolean isExpired() { 91 | return this.ttl < System.currentTimeMillis(); 92 | } 93 | 94 | /** True if a refresh is needed from the original data source. */ 95 | public boolean refreshNeeded() { 96 | return this.softTtl < System.currentTimeMillis(); 97 | } 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/DefaultRetryPolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | /** 20 | * Default retry policy for requests. 21 | */ 22 | public class DefaultRetryPolicy implements RetryPolicy { 23 | /** The current timeout in milliseconds. */ 24 | private int mCurrentTimeoutMs; 25 | 26 | /** The current retry count. */ 27 | private int mCurrentRetryCount; 28 | 29 | /** The maximum number of attempts. */ 30 | private final int mMaxNumRetries; 31 | 32 | /** The backoff multiplier for the policy. */ 33 | private final float mBackoffMultiplier; 34 | 35 | /** The default socket timeout in milliseconds */ 36 | public static final int DEFAULT_TIMEOUT_MS = 2500; 37 | 38 | /** The default number of retries */ 39 | public static final int DEFAULT_MAX_RETRIES = 1; 40 | 41 | /** The default backoff multiplier */ 42 | public static final float DEFAULT_BACKOFF_MULT = 1f; 43 | 44 | /** 45 | * Constructs a new retry policy using the default timeouts. 46 | */ 47 | public DefaultRetryPolicy() { 48 | this(DEFAULT_TIMEOUT_MS, DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT); 49 | } 50 | 51 | /** 52 | * Constructs a new retry policy. 53 | * @param initialTimeoutMs The initial timeout for the policy. 54 | * @param maxNumRetries The maximum number of retries. 55 | * @param backoffMultiplier Backoff multiplier for the policy. 56 | */ 57 | public DefaultRetryPolicy(int initialTimeoutMs, int maxNumRetries, float backoffMultiplier) { 58 | mCurrentTimeoutMs = initialTimeoutMs; 59 | mMaxNumRetries = maxNumRetries; 60 | mBackoffMultiplier = backoffMultiplier; 61 | } 62 | 63 | /** 64 | * Returns the current timeout. 65 | */ 66 | @Override 67 | public int getCurrentTimeout() { 68 | return mCurrentTimeoutMs; 69 | } 70 | 71 | /** 72 | * Returns the current retry count. 73 | */ 74 | @Override 75 | public int getCurrentRetryCount() { 76 | return mCurrentRetryCount; 77 | } 78 | 79 | /** 80 | * Returns the backoff multiplier for the policy. 81 | */ 82 | public float getBackoffMultiplier() { 83 | return mBackoffMultiplier; 84 | } 85 | 86 | /** 87 | * Prepares for the next retry by applying a backoff to the timeout. 88 | * @param error The error code of the last attempt. 89 | */ 90 | @Override 91 | public void retry(VolleyError error) throws VolleyError { 92 | mCurrentRetryCount++; 93 | mCurrentTimeoutMs += (mCurrentTimeoutMs * mBackoffMultiplier); 94 | if (!hasAttemptRemaining()) { 95 | throw error; 96 | } 97 | } 98 | 99 | /** 100 | * Returns true if this policy has attempts remaining, false otherwise. 101 | */ 102 | protected boolean hasAttemptRemaining() { 103 | return mCurrentRetryCount <= mMaxNumRetries; 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/JsonRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import com.android.volley.NetworkResponse; 20 | import com.android.volley.Request; 21 | import com.android.volley.Response; 22 | import com.android.volley.Response.ErrorListener; 23 | import com.android.volley.Response.Listener; 24 | import com.android.volley.VolleyLog; 25 | 26 | import java.io.UnsupportedEncodingException; 27 | 28 | /** 29 | * A request for retrieving a T type response body at a given URL that also 30 | * optionally sends along a JSON body in the request specified. 31 | * 32 | * @param JSON type of response expected 33 | */ 34 | public abstract class JsonRequest extends Request { 35 | /** Default charset for JSON request. */ 36 | protected static final String PROTOCOL_CHARSET = "utf-8"; 37 | 38 | /** Content type for request. */ 39 | private static final String PROTOCOL_CONTENT_TYPE = 40 | String.format("application/json; charset=%s", PROTOCOL_CHARSET); 41 | 42 | private final Listener mListener; 43 | private final String mRequestBody; 44 | 45 | /** 46 | * Deprecated constructor for a JsonRequest which defaults to GET unless {@link #getPostBody()} 47 | * or {@link #getPostParams()} is overridden (which defaults to POST). 48 | * 49 | * @deprecated Use {@link #JsonRequest(int, String, String, Listener, ErrorListener)}. 50 | */ 51 | public JsonRequest(String url, String requestBody, Listener listener, 52 | ErrorListener errorListener) { 53 | this(Method.DEPRECATED_GET_OR_POST, url, requestBody, listener, errorListener); 54 | } 55 | 56 | public JsonRequest(int method, String url, String requestBody, Listener listener, 57 | ErrorListener errorListener) { 58 | super(method, url, errorListener); 59 | mListener = listener; 60 | mRequestBody = requestBody; 61 | } 62 | 63 | @Override 64 | protected void deliverResponse(T response) { 65 | mListener.onResponse(response); 66 | } 67 | 68 | @Override 69 | abstract protected Response parseNetworkResponse(NetworkResponse response); 70 | 71 | /** 72 | * @deprecated Use {@link #getBodyContentType()}. 73 | */ 74 | @Override 75 | public String getPostBodyContentType() { 76 | return getBodyContentType(); 77 | } 78 | 79 | /** 80 | * @deprecated Use {@link #getBody()}. 81 | */ 82 | @Override 83 | public byte[] getPostBody() { 84 | return getBody(); 85 | } 86 | 87 | @Override 88 | public String getBodyContentType() { 89 | return PROTOCOL_CONTENT_TYPE; 90 | } 91 | 92 | @Override 93 | public byte[] getBody() { 94 | try { 95 | return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET); 96 | } catch (UnsupportedEncodingException uee) { 97 | VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", 98 | mRequestBody, PROTOCOL_CHARSET); 99 | return null; 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/build.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | 29 | 30 | 31 | 35 | 36 | 37 | 38 | 39 | 40 | 49 | 50 | 51 | 52 | 56 | 57 | 69 | 70 | 71 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/AndroidAuthenticator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import com.android.volley.AuthFailureError; 20 | 21 | import android.accounts.Account; 22 | import android.accounts.AccountManager; 23 | import android.accounts.AccountManagerFuture; 24 | import android.content.Context; 25 | import android.content.Intent; 26 | import android.os.Bundle; 27 | 28 | /** 29 | * An Authenticator that uses {@link AccountManager} to get auth 30 | * tokens of a specified type for a specified account. 31 | */ 32 | public class AndroidAuthenticator implements Authenticator { 33 | private final AccountManager mAccountManager; 34 | private final Account mAccount; 35 | private final String mAuthTokenType; 36 | private final boolean mNotifyAuthFailure; 37 | 38 | /** 39 | * Creates a new authenticator. 40 | * @param context Context for accessing AccountManager 41 | * @param account Account to authenticate as 42 | * @param authTokenType Auth token type passed to AccountManager 43 | */ 44 | public AndroidAuthenticator(Context context, Account account, String authTokenType) { 45 | this(context, account, authTokenType, false); 46 | } 47 | 48 | /** 49 | * Creates a new authenticator. 50 | * @param context Context for accessing AccountManager 51 | * @param account Account to authenticate as 52 | * @param authTokenType Auth token type passed to AccountManager 53 | * @param notifyAuthFailure Whether to raise a notification upon auth failure 54 | */ 55 | public AndroidAuthenticator(Context context, Account account, String authTokenType, 56 | boolean notifyAuthFailure) { 57 | this(AccountManager.get(context), account, authTokenType, notifyAuthFailure); 58 | } 59 | 60 | // Visible for testing. Allows injection of a mock AccountManager. 61 | AndroidAuthenticator(AccountManager accountManager, Account account, 62 | String authTokenType, boolean notifyAuthFailure) { 63 | mAccountManager = accountManager; 64 | mAccount = account; 65 | mAuthTokenType = authTokenType; 66 | mNotifyAuthFailure = notifyAuthFailure; 67 | } 68 | 69 | /** 70 | * Returns the Account being used by this authenticator. 71 | */ 72 | public Account getAccount() { 73 | return mAccount; 74 | } 75 | 76 | // TODO: Figure out what to do about notifyAuthFailure 77 | @SuppressWarnings("deprecation") 78 | @Override 79 | public String getAuthToken() throws AuthFailureError { 80 | AccountManagerFuture future = mAccountManager.getAuthToken(mAccount, 81 | mAuthTokenType, mNotifyAuthFailure, null, null); 82 | Bundle result; 83 | try { 84 | result = future.getResult(); 85 | } catch (Exception e) { 86 | throw new AuthFailureError("Error while retrieving auth token", e); 87 | } 88 | String authToken = null; 89 | if (future.isDone() && !future.isCancelled()) { 90 | if (result.containsKey(AccountManager.KEY_INTENT)) { 91 | Intent intent = result.getParcelable(AccountManager.KEY_INTENT); 92 | throw new AuthFailureError(intent); 93 | } 94 | authToken = result.getString(AccountManager.KEY_AUTHTOKEN); 95 | } 96 | if (authToken == null) { 97 | throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType); 98 | } 99 | 100 | return authToken; 101 | } 102 | 103 | @Override 104 | public void invalidateAuthToken(String authToken) { 105 | mAccountManager.invalidateAuthToken(mAccount.type, authToken); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/ExecutorDelivery.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | import android.os.Handler; 20 | 21 | import java.util.concurrent.Executor; 22 | 23 | /** 24 | * Delivers responses and errors. 25 | */ 26 | public class ExecutorDelivery implements ResponseDelivery { 27 | /** Used for posting responses, typically to the main thread. */ 28 | private final Executor mResponsePoster; 29 | 30 | /** 31 | * Creates a new response delivery interface. 32 | * @param handler {@link Handler} to post responses on 33 | */ 34 | public ExecutorDelivery(final Handler handler) { 35 | // Make an Executor that just wraps the handler. 36 | mResponsePoster = new Executor() { 37 | @Override 38 | public void execute(Runnable command) { 39 | handler.post(command); 40 | } 41 | }; 42 | } 43 | 44 | /** 45 | * Creates a new response delivery interface, mockable version 46 | * for testing. 47 | * @param executor For running delivery tasks 48 | */ 49 | public ExecutorDelivery(Executor executor) { 50 | mResponsePoster = executor; 51 | } 52 | 53 | @Override 54 | public void postResponse(Request request, Response response) { 55 | postResponse(request, response, null); 56 | } 57 | 58 | @Override 59 | public void postResponse(Request request, Response response, Runnable runnable) { 60 | request.markDelivered(); 61 | request.addMarker("post-response"); 62 | mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable)); 63 | } 64 | 65 | @Override 66 | public void postError(Request request, VolleyError error) { 67 | request.addMarker("post-error"); 68 | Response response = Response.error(error); 69 | mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, null)); 70 | } 71 | 72 | /** 73 | * A Runnable used for delivering network responses to a listener on the 74 | * main thread. 75 | */ 76 | @SuppressWarnings("rawtypes") 77 | private class ResponseDeliveryRunnable implements Runnable { 78 | private final Request mRequest; 79 | private final Response mResponse; 80 | private final Runnable mRunnable; 81 | 82 | public ResponseDeliveryRunnable(Request request, Response response, Runnable runnable) { 83 | mRequest = request; 84 | mResponse = response; 85 | mRunnable = runnable; 86 | } 87 | 88 | @SuppressWarnings("unchecked") 89 | @Override 90 | public void run() { 91 | // If this request has canceled, finish it and don't deliver. 92 | if (mRequest.isCanceled()) { 93 | mRequest.finish("canceled-at-delivery"); 94 | return; 95 | } 96 | 97 | // Deliver a normal response or error, depending. 98 | if (mResponse.isSuccess()) { 99 | mRequest.deliverResponse(mResponse.result); 100 | } else { 101 | mRequest.deliverError(mResponse.error); 102 | } 103 | 104 | // If this is an intermediate response, add a marker, otherwise we're done 105 | // and the request can be finished. 106 | if (mResponse.intermediate) { 107 | mRequest.addMarker("intermediate-response"); 108 | } else { 109 | mRequest.finish("done"); 110 | } 111 | 112 | // If we have been provided a post-delivery runnable, run it. 113 | if (mRunnable != null) { 114 | mRunnable.run(); 115 | } 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/RequestFuture.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import com.android.volley.Request; 20 | import com.android.volley.Response; 21 | import com.android.volley.VolleyError; 22 | 23 | import java.util.concurrent.ExecutionException; 24 | import java.util.concurrent.Future; 25 | import java.util.concurrent.TimeUnit; 26 | import java.util.concurrent.TimeoutException; 27 | 28 | /** 29 | * A Future that represents a Volley request. 30 | * 31 | * Used by providing as your response and error listeners. For example: 32 | *
 33 |  * RequestFuture<JSONObject> future = RequestFuture.newFuture();
 34 |  * MyRequest request = new MyRequest(URL, future, future);
 35 |  *
 36 |  * // If you want to be able to cancel the request:
 37 |  * future.setRequest(requestQueue.add(request));
 38 |  *
 39 |  * // Otherwise:
 40 |  * requestQueue.add(request);
 41 |  *
 42 |  * try {
 43 |  *   JSONObject response = future.get();
 44 |  *   // do something with response
 45 |  * } catch (InterruptedException e) {
 46 |  *   // handle the error
 47 |  * } catch (ExecutionException e) {
 48 |  *   // handle the error
 49 |  * }
 50 |  * 
51 | * 52 | * @param The type of parsed response this future expects. 53 | */ 54 | public class RequestFuture implements Future, Response.Listener, 55 | Response.ErrorListener { 56 | private Request mRequest; 57 | private boolean mResultReceived = false; 58 | private T mResult; 59 | private VolleyError mException; 60 | 61 | public static RequestFuture newFuture() { 62 | return new RequestFuture(); 63 | } 64 | 65 | private RequestFuture() {} 66 | 67 | public void setRequest(Request request) { 68 | mRequest = request; 69 | } 70 | 71 | @Override 72 | public synchronized boolean cancel(boolean mayInterruptIfRunning) { 73 | if (mRequest == null) { 74 | return false; 75 | } 76 | 77 | if (!isDone()) { 78 | mRequest.cancel(); 79 | return true; 80 | } else { 81 | return false; 82 | } 83 | } 84 | 85 | @Override 86 | public T get() throws InterruptedException, ExecutionException { 87 | try { 88 | return doGet(null); 89 | } catch (TimeoutException e) { 90 | throw new AssertionError(e); 91 | } 92 | } 93 | 94 | @Override 95 | public T get(long timeout, TimeUnit unit) 96 | throws InterruptedException, ExecutionException, TimeoutException { 97 | return doGet(TimeUnit.MILLISECONDS.convert(timeout, unit)); 98 | } 99 | 100 | private synchronized T doGet(Long timeoutMs) 101 | throws InterruptedException, ExecutionException, TimeoutException { 102 | if (mException != null) { 103 | throw new ExecutionException(mException); 104 | } 105 | 106 | if (mResultReceived) { 107 | return mResult; 108 | } 109 | 110 | if (timeoutMs == null) { 111 | wait(0); 112 | } else if (timeoutMs > 0) { 113 | wait(timeoutMs); 114 | } 115 | 116 | if (mException != null) { 117 | throw new ExecutionException(mException); 118 | } 119 | 120 | if (!mResultReceived) { 121 | throw new TimeoutException(); 122 | } 123 | 124 | return mResult; 125 | } 126 | 127 | @Override 128 | public boolean isCancelled() { 129 | if (mRequest == null) { 130 | return false; 131 | } 132 | return mRequest.isCanceled(); 133 | } 134 | 135 | @Override 136 | public synchronized boolean isDone() { 137 | return mResultReceived || mException != null || isCancelled(); 138 | } 139 | 140 | @Override 141 | public synchronized void onResponse(T response) { 142 | mResultReceived = true; 143 | mResult = response; 144 | notifyAll(); 145 | } 146 | 147 | @Override 148 | public synchronized void onErrorResponse(VolleyError error) { 149 | mException = error; 150 | notifyAll(); 151 | } 152 | } 153 | 154 | -------------------------------------------------------------------------------- /app/src/main/java/com/tsy12321/netdemo/http/glue/MyOkHttp.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo.http.glue; 2 | 3 | import android.content.Context; 4 | import android.os.Handler; 5 | 6 | import com.tsy12321.netdemo.http.MyHttpJsonResponseHandler; 7 | import com.tsy12321.netdemo.http.lib.LibOkHttp; 8 | 9 | import org.json.JSONException; 10 | import org.json.JSONObject; 11 | 12 | import java.io.IOException; 13 | import java.util.Map; 14 | 15 | import okhttp3.Call; 16 | import okhttp3.Callback; 17 | import okhttp3.Response; 18 | 19 | /** 20 | * Created by tsy on 16/5/23. 21 | */ 22 | public class MyOkHttp { 23 | 24 | public static void doLibOkHttpPost(Context context, String url, Map params, final MyHttpJsonResponseHandler responseHandler) { 25 | final Handler handler = new Handler(); 26 | LibOkHttp.post(context, url, params, new Callback() { 27 | @Override 28 | public void onFailure(Call call, IOException e) { 29 | handler.post(new Runnable() { 30 | @Override 31 | public void run() { 32 | responseHandler.onFailure(0, "IOException"); 33 | } 34 | }); 35 | } 36 | 37 | @Override 38 | public void onResponse(Call call, final Response response) throws IOException { 39 | handler.post(new Runnable() { 40 | @Override 41 | public void run() { 42 | String response_body = ""; 43 | try { 44 | response_body = response.body().string(); 45 | if(response.isSuccessful()) { 46 | JSONObject body = new JSONObject(response_body); 47 | responseHandler.onSuccess(response.code(), body); 48 | } else { 49 | responseHandler.onFailure(response.code(), response_body); 50 | } 51 | 52 | } catch (IOException e) { 53 | e.printStackTrace(); 54 | responseHandler.onFailure(response.code(), "IOException"); 55 | } catch (JSONException e) { 56 | e.printStackTrace(); 57 | responseHandler.onFailure(response.code(), "parse json error:" + response_body); 58 | } 59 | } 60 | }); 61 | } 62 | }); 63 | } 64 | 65 | public static void doLibOkHttpGet(Context context, String url, Map params, final MyHttpJsonResponseHandler responseHandler) { 66 | //拼接url 67 | if(params != null && params.size() > 0) { 68 | int i = 0; 69 | for (Map.Entry entry : params.entrySet()) { 70 | if(i++ == 0) { 71 | url = url + "?" + entry.getKey() + "=" + entry.getValue(); 72 | } else { 73 | url = url + "&" + entry.getKey() + "=" + entry.getValue(); 74 | } 75 | } 76 | } 77 | 78 | final Handler handler = new Handler(); 79 | LibOkHttp.get(context, url, new Callback() { 80 | @Override 81 | public void onFailure(Call call, IOException e) { 82 | handler.post(new Runnable() { 83 | @Override 84 | public void run() { 85 | responseHandler.onFailure(0, "IOException"); 86 | } 87 | }); 88 | } 89 | 90 | @Override 91 | public void onResponse(Call call, final Response response) throws IOException { 92 | handler.post(new Runnable() { 93 | @Override 94 | public void run() { 95 | String response_body = ""; 96 | try { 97 | response_body = response.body().string(); 98 | if(response.isSuccessful()) { 99 | JSONObject body = new JSONObject(response_body); 100 | responseHandler.onSuccess(response.code(), body); 101 | } else { 102 | responseHandler.onFailure(response.code(), response_body); 103 | } 104 | 105 | } catch (IOException e) { 106 | e.printStackTrace(); 107 | responseHandler.onFailure(response.code(), "IOException"); 108 | } catch (JSONException e) { 109 | e.printStackTrace(); 110 | responseHandler.onFailure(response.code(), "parse json error:" + response_body); 111 | } 112 | } 113 | }); 114 | } 115 | }); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /app/src/main/java/com/tsy12321/netdemo/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo; 2 | 3 | import android.os.Bundle; 4 | import android.os.Environment; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.util.Log; 7 | 8 | import com.tsy12321.netdemo.http.MyHttp; 9 | import com.tsy12321.netdemo.http.MyHttpFileResponseHandler; 10 | import com.tsy12321.netdemo.http.MyHttpJsonResponseHandler; 11 | 12 | import org.json.JSONObject; 13 | 14 | import java.io.File; 15 | import java.util.HashMap; 16 | import java.util.Map; 17 | 18 | public class MainActivity extends AppCompatActivity { 19 | 20 | @Override 21 | protected void onCreate(Bundle savedInstanceState) { 22 | super.onCreate(savedInstanceState); 23 | setContentView(R.layout.activity_main); 24 | 25 | doPostHttp(); 26 | //doGetHttp(); 27 | //doUpload(); 28 | //doDownload(); 29 | } 30 | 31 | //页面销毁关闭请求 防止crash 建议放到BaseActivity BaseFragrament里面 32 | @Override 33 | protected void onDestroy() { 34 | super.onDestroy(); 35 | 36 | MyHttp.cancelRequest(this); //页面退出 关闭所有请求 37 | } 38 | 39 | //post请求 40 | private void doPostHttp() { 41 | //文本参数 42 | Map params = new HashMap(); 43 | params.put("uid", "111"); 44 | 45 | //post 46 | MyHttp.doPost(this, "http://192.168.3.1/test_post.php", params, new MyHttpJsonResponseHandler() { 47 | @Override 48 | public void onSuccess(int statusCode, JSONObject response) { 49 | Log.i("tsy", "onSuccess status code=" + statusCode + " response=" + response); 50 | } 51 | 52 | @Override 53 | public void onFailure(int statusCode, String error_msg) { 54 | Log.i("tsy", "onFailure status code=" + statusCode + " error_msg=" + error_msg); 55 | } 56 | 57 | @Override 58 | public void onCancel() { 59 | Log.i("myhttp", "request on cancel"); 60 | } 61 | }); 62 | } 63 | 64 | //get请求 65 | private void doGetHttp() { 66 | //文本参数 67 | Map params = new HashMap(); 68 | params.put("uid", "111"); 69 | 70 | //get 71 | MyHttp.doGet(this, "http://192.168.3.1/get_attention_forum.php", params, new MyHttpJsonResponseHandler() { 72 | @Override 73 | public void onSuccess(int statusCode, JSONObject response) { 74 | Log.i("tsy", "onSuccess status code=" + statusCode + " response=" + response); 75 | } 76 | 77 | @Override 78 | public void onFailure(int statusCode, String error_msg) { 79 | Log.i("tsy", "onFailure status code=" + statusCode + " error_msg=" + error_msg); 80 | } 81 | 82 | @Override 83 | public void onCancel() { 84 | Log.i("myhttp", "request on cancel"); 85 | } 86 | }); 87 | } 88 | 89 | //上传文件 90 | private void doUpload() { 91 | //文件参数 92 | File file = new File(Environment.getExternalStorageDirectory() + "/girls/head/output_tmp2.jpg"); 93 | Map files = new HashMap(); 94 | files.put("avatar", file); 95 | 96 | //upload 97 | MyHttp.doUpload(this, "http://192.168.3.1/test_post.php", files, new MyHttpFileResponseHandler() { 98 | @Override 99 | public void onSuccess(int statusCode) { 100 | Log.i("tsy", "onSuccess status code=" + statusCode); 101 | } 102 | 103 | @Override 104 | public void onFailure(int statusCode, String error_msg) { 105 | Log.i("tsy", "onFailure status code=" + statusCode + " error_msg=" + error_msg); 106 | } 107 | 108 | @Override 109 | public void onProgress(long bytesWritten, long totalSize) { 110 | Log.i("tsy", String.format("Progress %d from %d (%2.0f%%)", bytesWritten, totalSize, (totalSize > 0) ? (bytesWritten * 1.0 / totalSize) * 100 : -1)); 111 | } 112 | 113 | @Override 114 | public void onCancel() { 115 | Log.i("tsy", "request on cancel"); 116 | } 117 | }); 118 | } 119 | 120 | //下载文件 121 | private void doDownload() { 122 | File file = new File(Environment.getExternalStorageDirectory() + "/girls/head/output_tmp2.jpg"); //下载后存储的file位置 123 | MyHttp.doDownload(this, "http://192.168.3.1/head.jpg", file, new MyHttpFileResponseHandler() { 124 | @Override 125 | public void onSuccess(int statusCode) { 126 | Log.i("tsy", "onSuccess status code=" + statusCode); 127 | } 128 | 129 | @Override 130 | public void onFailure(int statusCode, String error_msg) { 131 | Log.i("tsy", "onFailure status code=" + statusCode); 132 | } 133 | 134 | @Override 135 | public void onProgress(long bytesWritten, long totalSize) { 136 | Log.i("tsy", String.format("Progress %d from %d (%2.0f%%)", bytesWritten, totalSize, (totalSize > 0) ? (bytesWritten * 1.0 / totalSize) * 100 : -1)); 137 | } 138 | 139 | @Override 140 | public void onCancel() { 141 | Log.i("tsy", "request on cancel"); 142 | } 143 | }); 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/ByteArrayPool.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import java.util.ArrayList; 20 | import java.util.Collections; 21 | import java.util.Comparator; 22 | import java.util.LinkedList; 23 | import java.util.List; 24 | 25 | /** 26 | * ByteArrayPool is a source and repository of byte[] objects. Its purpose is to 27 | * supply those buffers to consumers who need to use them for a short period of time and then 28 | * dispose of them. Simply creating and disposing such buffers in the conventional manner can 29 | * considerable heap churn and garbage collection delays on Android, which lacks good management of 30 | * short-lived heap objects. It may be advantageous to trade off some memory in the form of a 31 | * permanently allocated pool of buffers in order to gain heap performance improvements; that is 32 | * what this class does. 33 | *

34 | * A good candidate user for this class is something like an I/O system that uses large temporary 35 | * byte[] buffers to copy data around. In these use cases, often the consumer wants 36 | * the buffer to be a certain minimum size to ensure good performance (e.g. when copying data chunks 37 | * off of a stream), but doesn't mind if the buffer is larger than the minimum. Taking this into 38 | * account and also to maximize the odds of being able to reuse a recycled buffer, this class is 39 | * free to return buffers larger than the requested size. The caller needs to be able to gracefully 40 | * deal with getting buffers any size over the minimum. 41 | *

42 | * If there is not a suitably-sized buffer in its recycling pool when a buffer is requested, this 43 | * class will allocate a new buffer and return it. 44 | *

45 | * This class has no special ownership of buffers it creates; the caller is free to take a buffer 46 | * it receives from this pool, use it permanently, and never return it to the pool; additionally, 47 | * it is not harmful to return to this pool a buffer that was allocated elsewhere, provided there 48 | * are no other lingering references to it. 49 | *

50 | * This class ensures that the total size of the buffers in its recycling pool never exceeds a 51 | * certain byte limit. When a buffer is returned that would cause the pool to exceed the limit, 52 | * least-recently-used buffers are disposed. 53 | */ 54 | public class ByteArrayPool { 55 | /** The buffer pool, arranged both by last use and by buffer size */ 56 | private List mBuffersByLastUse = new LinkedList(); 57 | private List mBuffersBySize = new ArrayList(64); 58 | 59 | /** The total size of the buffers in the pool */ 60 | private int mCurrentSize = 0; 61 | 62 | /** 63 | * The maximum aggregate size of the buffers in the pool. Old buffers are discarded to stay 64 | * under this limit. 65 | */ 66 | private final int mSizeLimit; 67 | 68 | /** Compares buffers by size */ 69 | protected static final Comparator BUF_COMPARATOR = new Comparator() { 70 | @Override 71 | public int compare(byte[] lhs, byte[] rhs) { 72 | return lhs.length - rhs.length; 73 | } 74 | }; 75 | 76 | /** 77 | * @param sizeLimit the maximum size of the pool, in bytes 78 | */ 79 | public ByteArrayPool(int sizeLimit) { 80 | mSizeLimit = sizeLimit; 81 | } 82 | 83 | /** 84 | * Returns a buffer from the pool if one is available in the requested size, or allocates a new 85 | * one if a pooled one is not available. 86 | * 87 | * @param len the minimum size, in bytes, of the requested buffer. The returned buffer may be 88 | * larger. 89 | * @return a byte[] buffer is always returned. 90 | */ 91 | public synchronized byte[] getBuf(int len) { 92 | for (int i = 0; i < mBuffersBySize.size(); i++) { 93 | byte[] buf = mBuffersBySize.get(i); 94 | if (buf.length >= len) { 95 | mCurrentSize -= buf.length; 96 | mBuffersBySize.remove(i); 97 | mBuffersByLastUse.remove(buf); 98 | return buf; 99 | } 100 | } 101 | return new byte[len]; 102 | } 103 | 104 | /** 105 | * Returns a buffer to the pool, throwing away old buffers if the pool would exceed its allotted 106 | * size. 107 | * 108 | * @param buf the buffer to return to the pool. 109 | */ 110 | public synchronized void returnBuf(byte[] buf) { 111 | if (buf == null || buf.length > mSizeLimit) { 112 | return; 113 | } 114 | mBuffersByLastUse.add(buf); 115 | int pos = Collections.binarySearch(mBuffersBySize, buf, BUF_COMPARATOR); 116 | if (pos < 0) { 117 | pos = -pos - 1; 118 | } 119 | mBuffersBySize.add(pos, buf); 120 | mCurrentSize += buf.length; 121 | trim(); 122 | } 123 | 124 | /** 125 | * Removes buffers from the pool until it is under its size limit. 126 | */ 127 | private synchronized void trim() { 128 | while (mCurrentSize > mSizeLimit) { 129 | byte[] buf = mBuffersByLastUse.remove(0); 130 | mBuffersBySize.remove(buf); 131 | mCurrentSize -= buf.length; 132 | } 133 | } 134 | 135 | } 136 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.android.volley 6 | volley 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | volley 11 | http://android.com 12 | 13 | 14 | UTF-8 15 | 16 | 1.6 17 | 18 | 19 | 20 | 21 | com.google.android 22 | android 23 | 4.1.1.4 24 | 25 | 26 | junit 27 | junit 28 | 4.10 29 | test 30 | 31 | 32 | org.robolectric 33 | robolectric 34 | 2.2 35 | test 36 | 37 | 38 | org.mockito 39 | mockito-core 40 | 1.9.5 41 | test 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | com.jayway.maven.plugins.android.generation2 50 | android-maven-plugin 51 | 3.8.1 52 | 53 | 54 | 19 55 | 56 | 57 | 58 | 59 | 60 | org.apache.maven.plugins 61 | maven-compiler-plugin 62 | 3.0 63 | 64 | ${java.version} 65 | ${java.version} 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | debug 75 | 76 | true 77 | 78 | performDebugBuild 79 | true 80 | 81 | 82 | 83 | 84 | 85 | org.apache.maven.plugins 86 | maven-surefire-plugin 87 | 2.18.1 88 | 89 | 90 | default-test 91 | 92 | ${surefireArgLine} 93 | 94 | 95 | 96 | 97 | 98 | org.jacoco 99 | jacoco-maven-plugin 100 | 102 | 0.7.2.201409121644 103 | 104 | 105 | pre-unit-test 106 | 107 | prepare-agent 108 | 109 | 110 | ${project.build.directory}/surefire-reports/jacoco-ut.exec 111 | surefireArgLine 112 | 113 | 114 | 115 | jacoco-report 116 | post-integration-test 117 | 118 | report 119 | check 120 | 121 | 122 | ${project.build.directory}/surefire-reports/jacoco-ut.exec 123 | ${project.build.directory}/jacoco-report 124 | 125 | 126 | BUNDLE 127 | 128 | 129 | INSTRUCTION 130 | COVEREDRATIO 131 | 0.40 132 | 133 | 134 | 141 | 142 | 143 | 144 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/NetworkDispatcher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | import android.annotation.TargetApi; 20 | import android.net.TrafficStats; 21 | import android.os.Build; 22 | import android.os.Process; 23 | import android.os.SystemClock; 24 | 25 | import java.util.concurrent.BlockingQueue; 26 | 27 | /** 28 | * Provides a thread for performing network dispatch from a queue of requests. 29 | * 30 | * Requests added to the specified queue are processed from the network via a 31 | * specified {@link Network} interface. Responses are committed to cache, if 32 | * eligible, using a specified {@link Cache} interface. Valid responses and 33 | * errors are posted back to the caller via a {@link ResponseDelivery}. 34 | */ 35 | public class NetworkDispatcher extends Thread { 36 | /** The queue of requests to service. */ 37 | private final BlockingQueue> mQueue; 38 | /** The network interface for processing requests. */ 39 | private final Network mNetwork; 40 | /** The cache to write to. */ 41 | private final Cache mCache; 42 | /** For posting responses and errors. */ 43 | private final ResponseDelivery mDelivery; 44 | /** Used for telling us to die. */ 45 | private volatile boolean mQuit = false; 46 | 47 | /** 48 | * Creates a new network dispatcher thread. You must call {@link #start()} 49 | * in order to begin processing. 50 | * 51 | * @param queue Queue of incoming requests for triage 52 | * @param network Network interface to use for performing requests 53 | * @param cache Cache interface to use for writing responses to cache 54 | * @param delivery Delivery interface to use for posting responses 55 | */ 56 | public NetworkDispatcher(BlockingQueue> queue, 57 | Network network, Cache cache, 58 | ResponseDelivery delivery) { 59 | mQueue = queue; 60 | mNetwork = network; 61 | mCache = cache; 62 | mDelivery = delivery; 63 | } 64 | 65 | /** 66 | * Forces this dispatcher to quit immediately. If any requests are still in 67 | * the queue, they are not guaranteed to be processed. 68 | */ 69 | public void quit() { 70 | mQuit = true; 71 | interrupt(); 72 | } 73 | 74 | @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) 75 | private void addTrafficStatsTag(Request request) { 76 | // Tag the request (if API >= 14) 77 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 78 | TrafficStats.setThreadStatsTag(request.getTrafficStatsTag()); 79 | } 80 | } 81 | 82 | @Override 83 | public void run() { 84 | Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 85 | while (true) { 86 | long startTimeMs = SystemClock.elapsedRealtime(); 87 | Request request; 88 | try { 89 | // Take a request from the queue. 90 | request = mQueue.take(); 91 | } catch (InterruptedException e) { 92 | // We may have been interrupted because it was time to quit. 93 | if (mQuit) { 94 | return; 95 | } 96 | continue; 97 | } 98 | 99 | try { 100 | request.addMarker("network-queue-take"); 101 | 102 | // If the request was cancelled already, do not perform the 103 | // network request. 104 | if (request.isCanceled()) { 105 | request.finish("network-discard-cancelled"); 106 | continue; 107 | } 108 | 109 | addTrafficStatsTag(request); 110 | 111 | // Perform the network request. 112 | NetworkResponse networkResponse = mNetwork.performRequest(request); 113 | request.addMarker("network-http-complete"); 114 | 115 | // If the server returned 304 AND we delivered a response already, 116 | // we're done -- don't deliver a second identical response. 117 | if (networkResponse.notModified && request.hasHadResponseDelivered()) { 118 | request.finish("not-modified"); 119 | continue; 120 | } 121 | 122 | // Parse the response here on the worker thread. 123 | Response response = request.parseNetworkResponse(networkResponse); 124 | request.addMarker("network-parse-complete"); 125 | 126 | // Write to cache if applicable. 127 | // TODO: Only update cache metadata instead of entire record for 304s. 128 | if (request.shouldCache() && response.cacheEntry != null) { 129 | mCache.put(request.getCacheKey(), response.cacheEntry); 130 | request.addMarker("network-cache-written"); 131 | } 132 | 133 | // Post the response back. 134 | request.markDelivered(); 135 | mDelivery.postResponse(request, response); 136 | } catch (VolleyError volleyError) { 137 | volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs); 138 | parseAndDeliverNetworkError(request, volleyError); 139 | } catch (Exception e) { 140 | VolleyLog.e(e, "Unhandled exception %s", e.toString()); 141 | VolleyError volleyError = new VolleyError(e); 142 | volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs); 143 | mDelivery.postError(request, volleyError); 144 | } 145 | } 146 | } 147 | 148 | private void parseAndDeliverNetworkError(Request request, VolleyError error) { 149 | error = request.parseNetworkError(error); 150 | mDelivery.postError(request, error); 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/HttpHeaderParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import com.android.volley.Cache; 20 | import com.android.volley.NetworkResponse; 21 | 22 | import org.apache.http.impl.cookie.DateParseException; 23 | import org.apache.http.impl.cookie.DateUtils; 24 | import org.apache.http.protocol.HTTP; 25 | 26 | import java.util.Map; 27 | 28 | /** 29 | * Utility methods for parsing HTTP headers. 30 | */ 31 | public class HttpHeaderParser { 32 | 33 | /** 34 | * Extracts a {@link Cache.Entry} from a {@link NetworkResponse}. 35 | * 36 | * @param response The network response to parse headers from 37 | * @return a cache entry for the given response, or null if the response is not cacheable. 38 | */ 39 | public static Cache.Entry parseCacheHeaders(NetworkResponse response) { 40 | long now = System.currentTimeMillis(); 41 | 42 | Map headers = response.headers; 43 | 44 | long serverDate = 0; 45 | long lastModified = 0; 46 | long serverExpires = 0; 47 | long softExpire = 0; 48 | long finalExpire = 0; 49 | long maxAge = 0; 50 | long staleWhileRevalidate = 0; 51 | boolean hasCacheControl = false; 52 | boolean mustRevalidate = false; 53 | 54 | String serverEtag = null; 55 | String headerValue; 56 | 57 | headerValue = headers.get("Date"); 58 | if (headerValue != null) { 59 | serverDate = parseDateAsEpoch(headerValue); 60 | } 61 | 62 | headerValue = headers.get("Cache-Control"); 63 | if (headerValue != null) { 64 | hasCacheControl = true; 65 | String[] tokens = headerValue.split(","); 66 | for (int i = 0; i < tokens.length; i++) { 67 | String token = tokens[i].trim(); 68 | if (token.equals("no-cache") || token.equals("no-store")) { 69 | return null; 70 | } else if (token.startsWith("max-age=")) { 71 | try { 72 | maxAge = Long.parseLong(token.substring(8)); 73 | } catch (Exception e) { 74 | } 75 | } else if (token.startsWith("stale-while-revalidate=")) { 76 | try { 77 | staleWhileRevalidate = Long.parseLong(token.substring(23)); 78 | } catch (Exception e) { 79 | } 80 | } else if (token.equals("must-revalidate") || token.equals("proxy-revalidate")) { 81 | mustRevalidate = true; 82 | } 83 | } 84 | } 85 | 86 | headerValue = headers.get("Expires"); 87 | if (headerValue != null) { 88 | serverExpires = parseDateAsEpoch(headerValue); 89 | } 90 | 91 | headerValue = headers.get("Last-Modified"); 92 | if (headerValue != null) { 93 | lastModified = parseDateAsEpoch(headerValue); 94 | } 95 | 96 | serverEtag = headers.get("ETag"); 97 | 98 | // Cache-Control takes precedence over an Expires header, even if both exist and Expires 99 | // is more restrictive. 100 | if (hasCacheControl) { 101 | softExpire = now + maxAge * 1000; 102 | finalExpire = mustRevalidate 103 | ? softExpire 104 | : softExpire + staleWhileRevalidate * 1000; 105 | } else if (serverDate > 0 && serverExpires >= serverDate) { 106 | // Default semantic for Expire header in HTTP specification is softExpire. 107 | softExpire = now + (serverExpires - serverDate); 108 | finalExpire = softExpire; 109 | } 110 | 111 | Cache.Entry entry = new Cache.Entry(); 112 | entry.data = response.data; 113 | entry.etag = serverEtag; 114 | entry.softTtl = softExpire; 115 | entry.ttl = finalExpire; 116 | entry.serverDate = serverDate; 117 | entry.lastModified = lastModified; 118 | entry.responseHeaders = headers; 119 | 120 | return entry; 121 | } 122 | 123 | /** 124 | * Parse date in RFC1123 format, and return its value as epoch 125 | */ 126 | public static long parseDateAsEpoch(String dateStr) { 127 | try { 128 | // Parse date in RFC1123 format if this header contains one 129 | return DateUtils.parseDate(dateStr).getTime(); 130 | } catch (DateParseException e) { 131 | // Date in invalid format, fallback to 0 132 | return 0; 133 | } 134 | } 135 | 136 | /** 137 | * Retrieve a charset from headers 138 | * 139 | * @param headers An {@link java.util.Map} of headers 140 | * @param defaultCharset Charset to return if none can be found 141 | * @return Returns the charset specified in the Content-Type of this header, 142 | * or the defaultCharset if none can be found. 143 | */ 144 | public static String parseCharset(Map headers, String defaultCharset) { 145 | String contentType = headers.get(HTTP.CONTENT_TYPE); 146 | if (contentType != null) { 147 | String[] params = contentType.split(";"); 148 | for (int i = 1; i < params.length; i++) { 149 | String[] pair = params[i].trim().split("="); 150 | if (pair.length == 2) { 151 | if (pair[0].equals("charset")) { 152 | return pair[1]; 153 | } 154 | } 155 | } 156 | } 157 | 158 | return defaultCharset; 159 | } 160 | 161 | /** 162 | * Returns the charset specified in the Content-Type of this header, 163 | * or the HTTP default (ISO-8859-1) if none can be found. 164 | */ 165 | public static String parseCharset(Map headers) { 166 | return parseCharset(headers, HTTP.DEFAULT_CONTENT_CHARSET); 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/CacheDispatcher.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | import android.os.Process; 20 | 21 | import java.util.concurrent.BlockingQueue; 22 | 23 | /** 24 | * Provides a thread for performing cache triage on a queue of requests. 25 | * 26 | * Requests added to the specified cache queue are resolved from cache. 27 | * Any deliverable response is posted back to the caller via a 28 | * {@link ResponseDelivery}. Cache misses and responses that require 29 | * refresh are enqueued on the specified network queue for processing 30 | * by a {@link NetworkDispatcher}. 31 | */ 32 | public class CacheDispatcher extends Thread { 33 | 34 | private static final boolean DEBUG = VolleyLog.DEBUG; 35 | 36 | /** The queue of requests coming in for triage. */ 37 | private final BlockingQueue> mCacheQueue; 38 | 39 | /** The queue of requests going out to the network. */ 40 | private final BlockingQueue> mNetworkQueue; 41 | 42 | /** The cache to read from. */ 43 | private final Cache mCache; 44 | 45 | /** For posting responses. */ 46 | private final ResponseDelivery mDelivery; 47 | 48 | /** Used for telling us to die. */ 49 | private volatile boolean mQuit = false; 50 | 51 | /** 52 | * Creates a new cache triage dispatcher thread. You must call {@link #start()} 53 | * in order to begin processing. 54 | * 55 | * @param cacheQueue Queue of incoming requests for triage 56 | * @param networkQueue Queue to post requests that require network to 57 | * @param cache Cache interface to use for resolution 58 | * @param delivery Delivery interface to use for posting responses 59 | */ 60 | public CacheDispatcher( 61 | BlockingQueue> cacheQueue, BlockingQueue> networkQueue, 62 | Cache cache, ResponseDelivery delivery) { 63 | mCacheQueue = cacheQueue; 64 | mNetworkQueue = networkQueue; 65 | mCache = cache; 66 | mDelivery = delivery; 67 | } 68 | 69 | /** 70 | * Forces this dispatcher to quit immediately. If any requests are still in 71 | * the queue, they are not guaranteed to be processed. 72 | */ 73 | public void quit() { 74 | mQuit = true; 75 | interrupt(); 76 | } 77 | 78 | @Override 79 | public void run() { 80 | if (DEBUG) VolleyLog.v("start new dispatcher"); 81 | Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 82 | 83 | // Make a blocking call to initialize the cache. 84 | mCache.initialize(); 85 | 86 | while (true) { 87 | try { 88 | // Get a request from the cache triage queue, blocking until 89 | // at least one is available. 90 | final Request request = mCacheQueue.take(); 91 | request.addMarker("cache-queue-take"); 92 | 93 | // If the request has been canceled, don't bother dispatching it. 94 | if (request.isCanceled()) { 95 | request.finish("cache-discard-canceled"); 96 | continue; 97 | } 98 | 99 | // Attempt to retrieve this item from cache. 100 | Cache.Entry entry = mCache.get(request.getCacheKey()); 101 | if (entry == null) { 102 | request.addMarker("cache-miss"); 103 | // Cache miss; send off to the network dispatcher. 104 | mNetworkQueue.put(request); 105 | continue; 106 | } 107 | 108 | // If it is completely expired, just send it to the network. 109 | if (entry.isExpired()) { 110 | request.addMarker("cache-hit-expired"); 111 | request.setCacheEntry(entry); 112 | mNetworkQueue.put(request); 113 | continue; 114 | } 115 | 116 | // We have a cache hit; parse its data for delivery back to the request. 117 | request.addMarker("cache-hit"); 118 | Response response = request.parseNetworkResponse( 119 | new NetworkResponse(entry.data, entry.responseHeaders)); 120 | request.addMarker("cache-hit-parsed"); 121 | 122 | if (!entry.refreshNeeded()) { 123 | // Completely unexpired cache hit. Just deliver the response. 124 | mDelivery.postResponse(request, response); 125 | } else { 126 | // Soft-expired cache hit. We can deliver the cached response, 127 | // but we need to also send the request to the network for 128 | // refreshing. 129 | request.addMarker("cache-hit-refresh-needed"); 130 | request.setCacheEntry(entry); 131 | 132 | // Mark the response as intermediate. 133 | response.intermediate = true; 134 | 135 | // Post the intermediate response back to the user and have 136 | // the delivery then forward the request along to the network. 137 | mDelivery.postResponse(request, response, new Runnable() { 138 | @Override 139 | public void run() { 140 | try { 141 | mNetworkQueue.put(request); 142 | } catch (InterruptedException e) { 143 | // Not much we can do about this. 144 | } 145 | } 146 | }); 147 | } 148 | 149 | } catch (InterruptedException e) { 150 | // We may have been interrupted because it was time to quit. 151 | if (mQuit) { 152 | return; 153 | } 154 | continue; 155 | } 156 | } 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /app/src/main/java/com/tsy12321/netdemo/http/glue/MyAsyncHttp.java: -------------------------------------------------------------------------------- 1 | package com.tsy12321.netdemo.http.glue; 2 | 3 | import android.content.Context; 4 | 5 | import com.loopj.android.http.FileAsyncHttpResponseHandler; 6 | import com.loopj.android.http.JsonHttpResponseHandler; 7 | import com.loopj.android.http.RequestParams; 8 | import com.tsy12321.netdemo.http.MyHttpFileResponseHandler; 9 | import com.tsy12321.netdemo.http.MyHttpJsonResponseHandler; 10 | import com.tsy12321.netdemo.http.lib.LibAsyncHttp; 11 | 12 | import org.json.JSONObject; 13 | 14 | import java.io.File; 15 | import java.io.FileNotFoundException; 16 | import java.util.Map; 17 | 18 | import cz.msebera.android.httpclient.Header; 19 | 20 | /** 21 | * android-async-http 胶水层 22 | * Created by tsy on 16/5/17. 23 | */ 24 | public class MyAsyncHttp { 25 | 26 | /** 27 | * 调用async-http post请求 28 | * @param context 当前context 29 | * @param url 30 | * @param params 31 | * @param responseHandler 32 | */ 33 | public static void doLibAsyncHttpPost(Context context, String url, Mapparams, final MyHttpJsonResponseHandler responseHandler) { 34 | RequestParams rparams = new RequestParams(params); 35 | 36 | LibAsyncHttp.post(context, url, rparams, new JsonHttpResponseHandler() { 37 | @Override 38 | public void onSuccess(int statusCode, Header[] headers, JSONObject response) { 39 | responseHandler.onSuccess(statusCode, response); 40 | } 41 | 42 | @Override 43 | public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { 44 | responseHandler.onFailure(statusCode, responseString); 45 | } 46 | 47 | @Override 48 | public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { 49 | responseHandler.onFailure(statusCode, errorResponse + ""); 50 | } 51 | 52 | @Override 53 | public void onCancel() { 54 | responseHandler.onCancel(); 55 | } 56 | }); 57 | } 58 | 59 | /** 60 | * 调用async-http get请求 61 | * @param context 当前context 62 | * @param url 63 | * @param params 文本参数 64 | * @param responseHandler 65 | */ 66 | public static void doLibAsyncHttpGet(Context context, String url, Mapparams, final MyHttpJsonResponseHandler responseHandler) { 67 | //android-async-http 68 | RequestParams rparams = new RequestParams(params); 69 | 70 | LibAsyncHttp.get(context, url, rparams, new JsonHttpResponseHandler() { 71 | @Override 72 | public void onSuccess(int statusCode, Header[] headers, JSONObject response) { 73 | responseHandler.onSuccess(statusCode, response); 74 | } 75 | 76 | @Override 77 | public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { 78 | responseHandler.onFailure(statusCode, responseString); 79 | } 80 | 81 | @Override 82 | public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { 83 | responseHandler.onFailure(statusCode, errorResponse + ""); 84 | } 85 | 86 | @Override 87 | public void onCancel() { 88 | responseHandler.onCancel(); 89 | } 90 | }); 91 | } 92 | 93 | /** 94 | * 调用async-http 上传文件 95 | * @param context 当前context 96 | * @param url 97 | * @param files 98 | * @param responseHandler 99 | */ 100 | public static void doLibAsyncHttpUpload(Context context, String url, Mapfiles, final MyHttpFileResponseHandler responseHandler) { 101 | RequestParams rparams = new RequestParams(); 102 | 103 | try { 104 | if (files != null && files.size() > 0) { 105 | for (Map.Entry entry : files.entrySet()) { 106 | rparams.put(entry.getKey(), entry.getValue()); 107 | } 108 | } 109 | } catch (FileNotFoundException e) { 110 | e.printStackTrace(); 111 | responseHandler.onFailure(0, "FileNotFoundException"); 112 | return; 113 | } 114 | 115 | LibAsyncHttp.post(context, url, rparams, new JsonHttpResponseHandler() { 116 | @Override 117 | public void onSuccess(int statusCode, Header[] headers, JSONObject response) { 118 | responseHandler.onSuccess(statusCode); 119 | } 120 | 121 | @Override 122 | public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { 123 | responseHandler.onFailure(statusCode, responseString); 124 | } 125 | 126 | @Override 127 | public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) { 128 | responseHandler.onFailure(statusCode, errorResponse + ""); 129 | } 130 | 131 | @Override 132 | public void onProgress(long bytesWritten, long totalSize) { 133 | responseHandler.onProgress(bytesWritten, totalSize); 134 | } 135 | 136 | @Override 137 | public void onCancel() { 138 | responseHandler.onCancel(); 139 | } 140 | }); 141 | } 142 | 143 | /** 144 | * 调用async-http 下载文件 145 | * @param context 当前context 146 | * @param url 147 | * @param target 下载后存放file 148 | * @param responseHandler 149 | */ 150 | public static void doLibAsyncHttpDownload(Context context, String url, File target, final MyHttpFileResponseHandler responseHandler) { 151 | LibAsyncHttp.get(context, url, null, new FileAsyncHttpResponseHandler(target) { 152 | @Override 153 | public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) { 154 | responseHandler.onFailure(statusCode, "download error"); 155 | } 156 | 157 | @Override 158 | public void onSuccess(int statusCode, Header[] headers, File file) { 159 | responseHandler.onSuccess(statusCode); 160 | } 161 | 162 | @Override 163 | public void onProgress(long bytesWritten, long totalSize) { 164 | responseHandler.onProgress(bytesWritten, totalSize); 165 | } 166 | 167 | @Override 168 | public void onCancel() { 169 | responseHandler.onCancel(); 170 | } 171 | }); 172 | } 173 | 174 | /** 175 | * 取消当前context下发起的所有请求 176 | * @param context 当前context 177 | */ 178 | public static void doLibAsyncHttpCacel(Context context) { 179 | LibAsyncHttp.cancelRequest(context); 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/VolleyLog.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley; 18 | 19 | import android.os.SystemClock; 20 | import android.util.Log; 21 | 22 | import java.util.ArrayList; 23 | import java.util.List; 24 | import java.util.Locale; 25 | 26 | /** 27 | * Logging helper class. 28 | *

29 | * to see Volley logs call:
30 | * {@code /platform-tools/adb shell setprop log.tag.Volley VERBOSE} 31 | */ 32 | public class VolleyLog { 33 | public static String TAG = "Volley"; 34 | 35 | public static boolean DEBUG = Log.isLoggable(TAG, Log.VERBOSE); 36 | 37 | /** 38 | * Customize the log tag for your application, so that other apps 39 | * using Volley don't mix their logs with yours. 40 | *
41 | * Enable the log property for your tag before starting your app: 42 | *
43 | * {@code adb shell setprop log.tag.<tag>} 44 | */ 45 | public static void setTag(String tag) { 46 | d("Changing log tag to %s", tag); 47 | TAG = tag; 48 | 49 | // Reinitialize the DEBUG "constant" 50 | DEBUG = Log.isLoggable(TAG, Log.VERBOSE); 51 | } 52 | 53 | public static void v(String format, Object... args) { 54 | if (DEBUG) { 55 | Log.v(TAG, buildMessage(format, args)); 56 | } 57 | } 58 | 59 | public static void d(String format, Object... args) { 60 | Log.d(TAG, buildMessage(format, args)); 61 | } 62 | 63 | public static void e(String format, Object... args) { 64 | Log.e(TAG, buildMessage(format, args)); 65 | } 66 | 67 | public static void e(Throwable tr, String format, Object... args) { 68 | Log.e(TAG, buildMessage(format, args), tr); 69 | } 70 | 71 | public static void wtf(String format, Object... args) { 72 | Log.wtf(TAG, buildMessage(format, args)); 73 | } 74 | 75 | public static void wtf(Throwable tr, String format, Object... args) { 76 | Log.wtf(TAG, buildMessage(format, args), tr); 77 | } 78 | 79 | /** 80 | * Formats the caller's provided message and prepends useful info like 81 | * calling thread ID and method name. 82 | */ 83 | private static String buildMessage(String format, Object... args) { 84 | String msg = (args == null) ? format : String.format(Locale.US, format, args); 85 | StackTraceElement[] trace = new Throwable().fillInStackTrace().getStackTrace(); 86 | 87 | String caller = ""; 88 | // Walk up the stack looking for the first caller outside of VolleyLog. 89 | // It will be at least two frames up, so start there. 90 | for (int i = 2; i < trace.length; i++) { 91 | Class clazz = trace[i].getClass(); 92 | if (!clazz.equals(VolleyLog.class)) { 93 | String callingClass = trace[i].getClassName(); 94 | callingClass = callingClass.substring(callingClass.lastIndexOf('.') + 1); 95 | callingClass = callingClass.substring(callingClass.lastIndexOf('$') + 1); 96 | 97 | caller = callingClass + "." + trace[i].getMethodName(); 98 | break; 99 | } 100 | } 101 | return String.format(Locale.US, "[%d] %s: %s", 102 | Thread.currentThread().getId(), caller, msg); 103 | } 104 | 105 | /** 106 | * A simple event log with records containing a name, thread ID, and timestamp. 107 | */ 108 | static class MarkerLog { 109 | public static final boolean ENABLED = VolleyLog.DEBUG; 110 | 111 | /** Minimum duration from first marker to last in an marker log to warrant logging. */ 112 | private static final long MIN_DURATION_FOR_LOGGING_MS = 0; 113 | 114 | private static class Marker { 115 | public final String name; 116 | public final long thread; 117 | public final long time; 118 | 119 | public Marker(String name, long thread, long time) { 120 | this.name = name; 121 | this.thread = thread; 122 | this.time = time; 123 | } 124 | } 125 | 126 | private final List mMarkers = new ArrayList(); 127 | private boolean mFinished = false; 128 | 129 | /** Adds a marker to this log with the specified name. */ 130 | public synchronized void add(String name, long threadId) { 131 | if (mFinished) { 132 | throw new IllegalStateException("Marker added to finished log"); 133 | } 134 | 135 | mMarkers.add(new Marker(name, threadId, SystemClock.elapsedRealtime())); 136 | } 137 | 138 | /** 139 | * Closes the log, dumping it to logcat if the time difference between 140 | * the first and last markers is greater than {@link #MIN_DURATION_FOR_LOGGING_MS}. 141 | * @param header Header string to print above the marker log. 142 | */ 143 | public synchronized void finish(String header) { 144 | mFinished = true; 145 | 146 | long duration = getTotalDuration(); 147 | if (duration <= MIN_DURATION_FOR_LOGGING_MS) { 148 | return; 149 | } 150 | 151 | long prevTime = mMarkers.get(0).time; 152 | d("(%-4d ms) %s", duration, header); 153 | for (Marker marker : mMarkers) { 154 | long thisTime = marker.time; 155 | d("(+%-4d) [%2d] %s", (thisTime - prevTime), marker.thread, marker.name); 156 | prevTime = thisTime; 157 | } 158 | } 159 | 160 | @Override 161 | protected void finalize() throws Throwable { 162 | // Catch requests that have been collected (and hence end-of-lifed) 163 | // but had no debugging output printed for them. 164 | if (!mFinished) { 165 | finish("Request on the loose"); 166 | e("Marker log finalized without finish() - uncaught exit point for request"); 167 | } 168 | } 169 | 170 | /** Returns the time difference between the first and last events in this log. */ 171 | private long getTotalDuration() { 172 | if (mMarkers.size() == 0) { 173 | return 0; 174 | } 175 | 176 | long first = mMarkers.get(0).time; 177 | long last = mMarkers.get(mMarkers.size() - 1).time; 178 | return last - first; 179 | } 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android-Http-Example 2 | Android网络请求的统一封装和调用.集成了android-async-http, volley, okhttp3等网络请求框架.可直接切换底层库. 3 | 4 | ## 1 简介 5 | 6 | ### 架构分层 7 | 8 | 总共分为三层: 9 | 1. 网络请求调用层. app统一调用该层接口和这层提供的回调,该层可以切换不同的网络请求库. 10 | 1. 网络请求库封装层. 封装了开源的Android网络请求库请求对外提供的方法. 11 | 1. 胶水层.负责调用层和封装层的连接.调用网络封装层的接口并将返回responseHandler转为调用层自定义的responseHandler. 12 | 13 | ### 功能 14 | 1. post get请求 15 | 1. cookie功能 16 | 1. 上传文件 17 | 1. 下载文件 18 | 1. 取消请求(页面销毁时可调用,防止页面销毁异步请求未取消而导致的crash) 19 | 20 | ### 集成的第三方网络请求库 21 | 22 | #### android-async-http 23 | 24 | 官网:http://loopj.com/android-async-http/ 25 | 26 | 文档:https://loopj.com/android-async-http/doc/ 27 | 28 | 示例:https://github.com/loopj/android-async-http/tree/master/sample/src/main/java/com/loopj/android/http/sample 29 | 30 | 注意点: 31 | 32 | 1. 取消请求接口cancelAllRequest,cancelRequest,cancelRequestByTag都必须在post,get时加上参数Context,否则cancel不起作用 33 | 34 | ### volley 35 | 36 | Git地址:https://android.googlesource.com/platform/frameworks/volley 37 | 38 | 官网地址:https://developer.android.com/training/volley/index.html?hl=zh-cn 39 | 40 | 郭霖的volley解析:http://blog.csdn.net/guolin_blog/article/details/17482095 41 | 42 | 注意点: 43 | 44 | 1. git clone后选用android-6.0.1_25 tag的版本,用master最新的引入出错 45 | 1. 将下载后的volley删除.git目录和src下test目录,然后拷贝到项目目录中 46 | 1. 修改项目setting.gradle添加":volley",并修改volley的gradle版本变为项目一样的版本,最好项目app添加dependency即引入volley成功 47 | 1. volley仅实现post和get请求,upload和download未实现.(volley不适合大数据下载文件下载等,因为volley会在parse过程中将数据缓存在内存中) 48 | 1. volley cacelRequest无onCancel事件触发 49 | 1. volley只能获取第一个cookie,如果需要多个cookie参考此[文章](http://www.w2bc.com/article/31961) 50 | 51 | ### okhttp3 52 | 53 | 官方地址: http://square.github.io/okhttp/ 54 | 55 | 注意点: 56 | 57 | ## 2 项目结构 58 | 59 | ### 统一调用层 60 | 1. MyHttp.java (**调用入口**) 61 | 1. MyHttpJsonResponseHandler.java (**请求回调json数据**) 62 | 1. MyHttpFileResponseHandler.java (**文件下载回调**) 63 | 64 | ### android-async-http 65 | 1. LibAsyncHttp.java (**封装了android-async-http对外提供的接口**) 66 | 1. MyAsyncHttp.java (**android-async-http和myhttp之间连接层**) 67 | 68 | ### volley 69 | 1. LibVolley.java (**封装了volley的对外post get接口**) 70 | 1. LibVolleyResponseModel.java (**volley返回数据封住**) 71 | 1. LibVolleyJSONObjectRequest.java (**volley自定义的request**) 72 | 1. MyVolley.java (**volley和myhttp之间连接层**) 73 | 74 | ### okhttp 75 | 1. LibOkHttp.java (**封装了okhttp的对外接口**) 76 | 1. MyOkHttp.java (**okhttp和myhttp之间连接层**) 77 | 78 | ## 3 调用示例 79 | 80 | ```java 81 | //post请求 82 | private void doPostHttp() { 83 | //文本参数 84 | Map params = new HashMap(); 85 | params.put("uid", "111"); 86 | 87 | //post 88 | MyHttp.doPost(this, "http://192.168.3.1/test_post.php", params, new MyHttpJsonResponseHandler() { 89 | @Override 90 | public void onSuccess(int statusCode, JSONObject response) { 91 | Log.i("tsy", "onSuccess status code=" + statusCode + " response=" + response); 92 | } 93 | 94 | @Override 95 | public void onFailure(int statusCode, String error_msg) { 96 | Log.i("tsy", "onFailure status code=" + statusCode + " error_msg=" + error_msg); 97 | } 98 | 99 | @Override 100 | public void onCancel() { 101 | Log.i("myhttp", "request on cancel"); 102 | } 103 | }); 104 | } 105 | 106 | //get请求 107 | private void doGetHttp() { 108 | //文本参数 109 | Map params = new HashMap(); 110 | params.put("uid", "111"); 111 | 112 | //get 113 | MyHttp.doGet(this, "http://192.168.3.1/test_post.php", params, new MyHttpJsonResponseHandler() { 114 | @Override 115 | public void onSuccess(int statusCode, JSONObject response) { 116 | Log.i("tsy", "onSuccess status code=" + statusCode + " response=" + response); 117 | } 118 | 119 | @Override 120 | public void onFailure(int statusCode, String error_msg) { 121 | Log.i("tsy", "onFailure status code=" + statusCode + " error_msg=" + error_msg); 122 | } 123 | 124 | @Override 125 | public void onCancel() { 126 | Log.i("myhttp", "request on cancel"); 127 | } 128 | }); 129 | } 130 | 131 | //上传文件 132 | private void doUpload() { 133 | //文件参数 134 | File file = new File(Environment.getExternalStorageDirectory() + "/girls/head/output_tmp2.jpg"); 135 | Map files = new HashMap(); 136 | files.put("avatar", file); 137 | 138 | //upload 139 | MyHttp.doUpload(this, "http://192.168.3.1/test_post.php", files, new MyHttpFileResponseHandler() { 140 | @Override 141 | public void onSuccess(int statusCode) { 142 | Log.i("tsy", "onSuccess status code=" + statusCode); 143 | } 144 | 145 | @Override 146 | public void onFailure(int statusCode, String error_msg) { 147 | Log.i("tsy", "onFailure status code=" + statusCode + " error_msg=" + error_msg); 148 | } 149 | 150 | @Override 151 | public void onProgress(long bytesWritten, long totalSize) { 152 | Log.i("tsy", String.format("Progress %d from %d" + 153 | " (%2.0f%%)", bytesWritten, totalSize, (totalSize > 0) ? (bytesWritten * 1.0 / totalSize) * 100 : -1)); 154 | } 155 | 156 | @Override 157 | public void onCancel() { 158 | Log.i("tsy", "request on cancel"); 159 | } 160 | }); 161 | } 162 | 163 | //下载文件 164 | private void doDownload() { 165 | File file = new File(Environment.getExternalStorageDirectory() + "/girls/head/output_tmp2.jpg"); //下载后存储的file位置 166 | MyHttp.doDownload(this, "http://192.168.3.1/head.jpg", file, new MyHttpFileResponseHandler() { 167 | @Override 168 | public void onSuccess(int statusCode) { 169 | Log.i("tsy", "onSuccess status code=" + statusCode); 170 | } 171 | 172 | @Override 173 | public void onFailure(int statusCode, String error_msg) { 174 | Log.i("tsy", "onFailure status code=" + statusCode); 175 | } 176 | 177 | @Override 178 | public void onProgress(long bytesWritten, long totalSize) { 179 | Log.i("tsy", String.format("Progress %d from %d (%2.0f%%)", bytesWritten, totalSize, (totalSize > 0) ? (bytesWritten * 1.0 / totalSize) * 100 : -1)); 180 | } 181 | 182 | @Override 183 | public void onCancel() { 184 | Log.i("tsy", "request on cancel"); 185 | } 186 | }); 187 | } 188 | 189 | //页面销毁关闭请求 防止crash 建议放到BaseActivity BaseFragrament里面 190 | @Override 191 | protected void onDestroy() { 192 | super.onDestroy(); 193 | 194 | MyHttp.cancelRequest(this); //页面退出 关闭所有请求 195 | } 196 | ``` 197 | 198 | ### 欢迎关注我的公众号 199 | 200 | ![我的公众号](https://github.com/tsy12321/PayAndroid/blob/master/wxmp_avatar.jpg) 201 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/HttpClientStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import com.android.volley.AuthFailureError; 20 | import com.android.volley.Request; 21 | import com.android.volley.Request.Method; 22 | 23 | import org.apache.http.HttpEntity; 24 | import org.apache.http.HttpResponse; 25 | import org.apache.http.NameValuePair; 26 | import org.apache.http.client.HttpClient; 27 | import org.apache.http.client.methods.HttpDelete; 28 | import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; 29 | import org.apache.http.client.methods.HttpGet; 30 | import org.apache.http.client.methods.HttpHead; 31 | import org.apache.http.client.methods.HttpOptions; 32 | import org.apache.http.client.methods.HttpPost; 33 | import org.apache.http.client.methods.HttpPut; 34 | import org.apache.http.client.methods.HttpTrace; 35 | import org.apache.http.client.methods.HttpUriRequest; 36 | import org.apache.http.entity.ByteArrayEntity; 37 | import org.apache.http.message.BasicNameValuePair; 38 | import org.apache.http.params.HttpConnectionParams; 39 | import org.apache.http.params.HttpParams; 40 | 41 | import java.io.IOException; 42 | import java.net.URI; 43 | import java.util.ArrayList; 44 | import java.util.List; 45 | import java.util.Map; 46 | 47 | /** 48 | * An HttpStack that performs request over an {@link HttpClient}. 49 | */ 50 | public class HttpClientStack implements HttpStack { 51 | protected final HttpClient mClient; 52 | 53 | private final static String HEADER_CONTENT_TYPE = "Content-Type"; 54 | 55 | public HttpClientStack(HttpClient client) { 56 | mClient = client; 57 | } 58 | 59 | private static void addHeaders(HttpUriRequest httpRequest, Map headers) { 60 | for (String key : headers.keySet()) { 61 | httpRequest.setHeader(key, headers.get(key)); 62 | } 63 | } 64 | 65 | @SuppressWarnings("unused") 66 | private static List getPostParameterPairs(Map postParams) { 67 | List result = new ArrayList(postParams.size()); 68 | for (String key : postParams.keySet()) { 69 | result.add(new BasicNameValuePair(key, postParams.get(key))); 70 | } 71 | return result; 72 | } 73 | 74 | @Override 75 | public HttpResponse performRequest(Request request, Map additionalHeaders) 76 | throws IOException, AuthFailureError { 77 | HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders); 78 | addHeaders(httpRequest, additionalHeaders); 79 | addHeaders(httpRequest, request.getHeaders()); 80 | onPrepareRequest(httpRequest); 81 | HttpParams httpParams = httpRequest.getParams(); 82 | int timeoutMs = request.getTimeoutMs(); 83 | // TODO: Reevaluate this connection timeout based on more wide-scale 84 | // data collection and possibly different for wifi vs. 3G. 85 | HttpConnectionParams.setConnectionTimeout(httpParams, 5000); 86 | HttpConnectionParams.setSoTimeout(httpParams, timeoutMs); 87 | return mClient.execute(httpRequest); 88 | } 89 | 90 | /** 91 | * Creates the appropriate subclass of HttpUriRequest for passed in request. 92 | */ 93 | @SuppressWarnings("deprecation") 94 | /* protected */ static HttpUriRequest createHttpRequest(Request request, 95 | Map additionalHeaders) throws AuthFailureError { 96 | switch (request.getMethod()) { 97 | case Method.DEPRECATED_GET_OR_POST: { 98 | // This is the deprecated way that needs to be handled for backwards compatibility. 99 | // If the request's post body is null, then the assumption is that the request is 100 | // GET. Otherwise, it is assumed that the request is a POST. 101 | byte[] postBody = request.getPostBody(); 102 | if (postBody != null) { 103 | HttpPost postRequest = new HttpPost(request.getUrl()); 104 | postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); 105 | HttpEntity entity; 106 | entity = new ByteArrayEntity(postBody); 107 | postRequest.setEntity(entity); 108 | return postRequest; 109 | } else { 110 | return new HttpGet(request.getUrl()); 111 | } 112 | } 113 | case Method.GET: 114 | return new HttpGet(request.getUrl()); 115 | case Method.DELETE: 116 | return new HttpDelete(request.getUrl()); 117 | case Method.POST: { 118 | HttpPost postRequest = new HttpPost(request.getUrl()); 119 | postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); 120 | setEntityIfNonEmptyBody(postRequest, request); 121 | return postRequest; 122 | } 123 | case Method.PUT: { 124 | HttpPut putRequest = new HttpPut(request.getUrl()); 125 | putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); 126 | setEntityIfNonEmptyBody(putRequest, request); 127 | return putRequest; 128 | } 129 | case Method.HEAD: 130 | return new HttpHead(request.getUrl()); 131 | case Method.OPTIONS: 132 | return new HttpOptions(request.getUrl()); 133 | case Method.TRACE: 134 | return new HttpTrace(request.getUrl()); 135 | case Method.PATCH: { 136 | HttpPatch patchRequest = new HttpPatch(request.getUrl()); 137 | patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); 138 | setEntityIfNonEmptyBody(patchRequest, request); 139 | return patchRequest; 140 | } 141 | default: 142 | throw new IllegalStateException("Unknown request method."); 143 | } 144 | } 145 | 146 | private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, 147 | Request request) throws AuthFailureError { 148 | byte[] body = request.getBody(); 149 | if (body != null) { 150 | HttpEntity entity = new ByteArrayEntity(body); 151 | httpRequest.setEntity(entity); 152 | } 153 | } 154 | 155 | /** 156 | * Called before the request is executed using the underlying HttpClient. 157 | * 158 | *

Overwrite in subclasses to augment the request.

159 | */ 160 | protected void onPrepareRequest(HttpUriRequest request) throws IOException { 161 | // Nothing. 162 | } 163 | 164 | /** 165 | * The HttpPatch class does not exist in the Android framework, so this has been defined here. 166 | */ 167 | public static final class HttpPatch extends HttpEntityEnclosingRequestBase { 168 | 169 | public final static String METHOD_NAME = "PATCH"; 170 | 171 | public HttpPatch() { 172 | super(); 173 | } 174 | 175 | public HttpPatch(final URI uri) { 176 | super(); 177 | setURI(uri); 178 | } 179 | 180 | /** 181 | * @throws IllegalArgumentException if the uri is invalid. 182 | */ 183 | public HttpPatch(final String uri) { 184 | super(); 185 | setURI(URI.create(uri)); 186 | } 187 | 188 | @Override 189 | public String getMethod() { 190 | return METHOD_NAME; 191 | } 192 | 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/NetworkImageView.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2013 The Android Open Source Project 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.android.volley.toolbox; 17 | 18 | import android.content.Context; 19 | import android.text.TextUtils; 20 | import android.util.AttributeSet; 21 | import android.view.ViewGroup.LayoutParams; 22 | import android.widget.ImageView; 23 | 24 | import com.android.volley.VolleyError; 25 | import com.android.volley.toolbox.ImageLoader.ImageContainer; 26 | import com.android.volley.toolbox.ImageLoader.ImageListener; 27 | 28 | /** 29 | * Handles fetching an image from a URL as well as the life-cycle of the 30 | * associated request. 31 | */ 32 | public class NetworkImageView extends ImageView { 33 | /** The URL of the network image to load */ 34 | private String mUrl; 35 | 36 | /** 37 | * Resource ID of the image to be used as a placeholder until the network image is loaded. 38 | */ 39 | private int mDefaultImageId; 40 | 41 | /** 42 | * Resource ID of the image to be used if the network response fails. 43 | */ 44 | private int mErrorImageId; 45 | 46 | /** Local copy of the ImageLoader. */ 47 | private ImageLoader mImageLoader; 48 | 49 | /** Current ImageContainer. (either in-flight or finished) */ 50 | private ImageContainer mImageContainer; 51 | 52 | public NetworkImageView(Context context) { 53 | this(context, null); 54 | } 55 | 56 | public NetworkImageView(Context context, AttributeSet attrs) { 57 | this(context, attrs, 0); 58 | } 59 | 60 | public NetworkImageView(Context context, AttributeSet attrs, int defStyle) { 61 | super(context, attrs, defStyle); 62 | } 63 | 64 | /** 65 | * Sets URL of the image that should be loaded into this view. Note that calling this will 66 | * immediately either set the cached image (if available) or the default image specified by 67 | * {@link NetworkImageView#setDefaultImageResId(int)} on the view. 68 | * 69 | * NOTE: If applicable, {@link NetworkImageView#setDefaultImageResId(int)} and 70 | * {@link NetworkImageView#setErrorImageResId(int)} should be called prior to calling 71 | * this function. 72 | * 73 | * @param url The URL that should be loaded into this ImageView. 74 | * @param imageLoader ImageLoader that will be used to make the request. 75 | */ 76 | public void setImageUrl(String url, ImageLoader imageLoader) { 77 | mUrl = url; 78 | mImageLoader = imageLoader; 79 | // The URL has potentially changed. See if we need to load it. 80 | loadImageIfNecessary(false); 81 | } 82 | 83 | /** 84 | * Sets the default image resource ID to be used for this view until the attempt to load it 85 | * completes. 86 | */ 87 | public void setDefaultImageResId(int defaultImage) { 88 | mDefaultImageId = defaultImage; 89 | } 90 | 91 | /** 92 | * Sets the error image resource ID to be used for this view in the event that the image 93 | * requested fails to load. 94 | */ 95 | public void setErrorImageResId(int errorImage) { 96 | mErrorImageId = errorImage; 97 | } 98 | 99 | /** 100 | * Loads the image for the view if it isn't already loaded. 101 | * @param isInLayoutPass True if this was invoked from a layout pass, false otherwise. 102 | */ 103 | void loadImageIfNecessary(final boolean isInLayoutPass) { 104 | int width = getWidth(); 105 | int height = getHeight(); 106 | ScaleType scaleType = getScaleType(); 107 | 108 | boolean wrapWidth = false, wrapHeight = false; 109 | if (getLayoutParams() != null) { 110 | wrapWidth = getLayoutParams().width == LayoutParams.WRAP_CONTENT; 111 | wrapHeight = getLayoutParams().height == LayoutParams.WRAP_CONTENT; 112 | } 113 | 114 | // if the view's bounds aren't known yet, and this is not a wrap-content/wrap-content 115 | // view, hold off on loading the image. 116 | boolean isFullyWrapContent = wrapWidth && wrapHeight; 117 | if (width == 0 && height == 0 && !isFullyWrapContent) { 118 | return; 119 | } 120 | 121 | // if the URL to be loaded in this view is empty, cancel any old requests and clear the 122 | // currently loaded image. 123 | if (TextUtils.isEmpty(mUrl)) { 124 | if (mImageContainer != null) { 125 | mImageContainer.cancelRequest(); 126 | mImageContainer = null; 127 | } 128 | setDefaultImageOrNull(); 129 | return; 130 | } 131 | 132 | // if there was an old request in this view, check if it needs to be canceled. 133 | if (mImageContainer != null && mImageContainer.getRequestUrl() != null) { 134 | if (mImageContainer.getRequestUrl().equals(mUrl)) { 135 | // if the request is from the same URL, return. 136 | return; 137 | } else { 138 | // if there is a pre-existing request, cancel it if it's fetching a different URL. 139 | mImageContainer.cancelRequest(); 140 | setDefaultImageOrNull(); 141 | } 142 | } 143 | 144 | // Calculate the max image width / height to use while ignoring WRAP_CONTENT dimens. 145 | int maxWidth = wrapWidth ? 0 : width; 146 | int maxHeight = wrapHeight ? 0 : height; 147 | 148 | // The pre-existing content of this view didn't match the current URL. Load the new image 149 | // from the network. 150 | ImageContainer newContainer = mImageLoader.get(mUrl, 151 | new ImageListener() { 152 | @Override 153 | public void onErrorResponse(VolleyError error) { 154 | if (mErrorImageId != 0) { 155 | setImageResource(mErrorImageId); 156 | } 157 | } 158 | 159 | @Override 160 | public void onResponse(final ImageContainer response, boolean isImmediate) { 161 | // If this was an immediate response that was delivered inside of a layout 162 | // pass do not set the image immediately as it will trigger a requestLayout 163 | // inside of a layout. Instead, defer setting the image by posting back to 164 | // the main thread. 165 | if (isImmediate && isInLayoutPass) { 166 | post(new Runnable() { 167 | @Override 168 | public void run() { 169 | onResponse(response, false); 170 | } 171 | }); 172 | return; 173 | } 174 | 175 | if (response.getBitmap() != null) { 176 | setImageBitmap(response.getBitmap()); 177 | } else if (mDefaultImageId != 0) { 178 | setImageResource(mDefaultImageId); 179 | } 180 | } 181 | }, maxWidth, maxHeight, scaleType); 182 | 183 | // update the ImageContainer to be the new bitmap container. 184 | mImageContainer = newContainer; 185 | } 186 | 187 | private void setDefaultImageOrNull() { 188 | if(mDefaultImageId != 0) { 189 | setImageResource(mDefaultImageId); 190 | } 191 | else { 192 | setImageBitmap(null); 193 | } 194 | } 195 | 196 | @Override 197 | protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 198 | super.onLayout(changed, left, top, right, bottom); 199 | loadImageIfNecessary(true); 200 | } 201 | 202 | @Override 203 | protected void onDetachedFromWindow() { 204 | if (mImageContainer != null) { 205 | // If the view was bound to an image request, cancel it and clear 206 | // out the image from the view. 207 | mImageContainer.cancelRequest(); 208 | setImageBitmap(null); 209 | // also clear out the container so we can reload the image if necessary. 210 | mImageContainer = null; 211 | } 212 | super.onDetachedFromWindow(); 213 | } 214 | 215 | @Override 216 | protected void drawableStateChanged() { 217 | super.drawableStateChanged(); 218 | invalidate(); 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/HurlStack.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import com.android.volley.AuthFailureError; 20 | import com.android.volley.Request; 21 | import com.android.volley.Request.Method; 22 | 23 | import org.apache.http.Header; 24 | import org.apache.http.HttpEntity; 25 | import org.apache.http.HttpResponse; 26 | import org.apache.http.ProtocolVersion; 27 | import org.apache.http.StatusLine; 28 | import org.apache.http.entity.BasicHttpEntity; 29 | import org.apache.http.message.BasicHeader; 30 | import org.apache.http.message.BasicHttpResponse; 31 | import org.apache.http.message.BasicStatusLine; 32 | 33 | import java.io.DataOutputStream; 34 | import java.io.IOException; 35 | import java.io.InputStream; 36 | import java.net.HttpURLConnection; 37 | import java.net.URL; 38 | import java.util.HashMap; 39 | import java.util.List; 40 | import java.util.Map; 41 | import java.util.Map.Entry; 42 | 43 | import javax.net.ssl.HttpsURLConnection; 44 | import javax.net.ssl.SSLSocketFactory; 45 | 46 | /** 47 | * An {@link HttpStack} based on {@link HttpURLConnection}. 48 | */ 49 | public class HurlStack implements HttpStack { 50 | 51 | private static final String HEADER_CONTENT_TYPE = "Content-Type"; 52 | 53 | /** 54 | * An interface for transforming URLs before use. 55 | */ 56 | public interface UrlRewriter { 57 | /** 58 | * Returns a URL to use instead of the provided one, or null to indicate 59 | * this URL should not be used at all. 60 | */ 61 | public String rewriteUrl(String originalUrl); 62 | } 63 | 64 | private final UrlRewriter mUrlRewriter; 65 | private final SSLSocketFactory mSslSocketFactory; 66 | 67 | public HurlStack() { 68 | this(null); 69 | } 70 | 71 | /** 72 | * @param urlRewriter Rewriter to use for request URLs 73 | */ 74 | public HurlStack(UrlRewriter urlRewriter) { 75 | this(urlRewriter, null); 76 | } 77 | 78 | /** 79 | * @param urlRewriter Rewriter to use for request URLs 80 | * @param sslSocketFactory SSL factory to use for HTTPS connections 81 | */ 82 | public HurlStack(UrlRewriter urlRewriter, SSLSocketFactory sslSocketFactory) { 83 | mUrlRewriter = urlRewriter; 84 | mSslSocketFactory = sslSocketFactory; 85 | } 86 | 87 | @Override 88 | public HttpResponse performRequest(Request request, Map additionalHeaders) 89 | throws IOException, AuthFailureError { 90 | String url = request.getUrl(); 91 | HashMap map = new HashMap(); 92 | map.putAll(request.getHeaders()); 93 | map.putAll(additionalHeaders); 94 | if (mUrlRewriter != null) { 95 | String rewritten = mUrlRewriter.rewriteUrl(url); 96 | if (rewritten == null) { 97 | throw new IOException("URL blocked by rewriter: " + url); 98 | } 99 | url = rewritten; 100 | } 101 | URL parsedUrl = new URL(url); 102 | HttpURLConnection connection = openConnection(parsedUrl, request); 103 | for (String headerName : map.keySet()) { 104 | connection.addRequestProperty(headerName, map.get(headerName)); 105 | } 106 | setConnectionParametersForRequest(connection, request); 107 | // Initialize HttpResponse with data from the HttpURLConnection. 108 | ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); 109 | int responseCode = connection.getResponseCode(); 110 | if (responseCode == -1) { 111 | // -1 is returned by getResponseCode() if the response code could not be retrieved. 112 | // Signal to the caller that something was wrong with the connection. 113 | throw new IOException("Could not retrieve response code from HttpUrlConnection."); 114 | } 115 | StatusLine responseStatus = new BasicStatusLine(protocolVersion, 116 | connection.getResponseCode(), connection.getResponseMessage()); 117 | BasicHttpResponse response = new BasicHttpResponse(responseStatus); 118 | response.setEntity(entityFromConnection(connection)); 119 | for (Entry> header : connection.getHeaderFields().entrySet()) { 120 | if (header.getKey() != null) { 121 | Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); 122 | response.addHeader(h); 123 | } 124 | } 125 | return response; 126 | } 127 | 128 | /** 129 | * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}. 130 | * @param connection 131 | * @return an HttpEntity populated with data from connection. 132 | */ 133 | private static HttpEntity entityFromConnection(HttpURLConnection connection) { 134 | BasicHttpEntity entity = new BasicHttpEntity(); 135 | InputStream inputStream; 136 | try { 137 | inputStream = connection.getInputStream(); 138 | } catch (IOException ioe) { 139 | inputStream = connection.getErrorStream(); 140 | } 141 | entity.setContent(inputStream); 142 | entity.setContentLength(connection.getContentLength()); 143 | entity.setContentEncoding(connection.getContentEncoding()); 144 | entity.setContentType(connection.getContentType()); 145 | return entity; 146 | } 147 | 148 | /** 149 | * Create an {@link HttpURLConnection} for the specified {@code url}. 150 | */ 151 | protected HttpURLConnection createConnection(URL url) throws IOException { 152 | return (HttpURLConnection) url.openConnection(); 153 | } 154 | 155 | /** 156 | * Opens an {@link HttpURLConnection} with parameters. 157 | * @param url 158 | * @return an open connection 159 | * @throws IOException 160 | */ 161 | private HttpURLConnection openConnection(URL url, Request request) throws IOException { 162 | HttpURLConnection connection = createConnection(url); 163 | 164 | int timeoutMs = request.getTimeoutMs(); 165 | connection.setConnectTimeout(timeoutMs); 166 | connection.setReadTimeout(timeoutMs); 167 | connection.setUseCaches(false); 168 | connection.setDoInput(true); 169 | 170 | // use caller-provided custom SslSocketFactory, if any, for HTTPS 171 | if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { 172 | ((HttpsURLConnection)connection).setSSLSocketFactory(mSslSocketFactory); 173 | } 174 | 175 | return connection; 176 | } 177 | 178 | @SuppressWarnings("deprecation") 179 | /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, 180 | Request request) throws IOException, AuthFailureError { 181 | switch (request.getMethod()) { 182 | case Method.DEPRECATED_GET_OR_POST: 183 | // This is the deprecated way that needs to be handled for backwards compatibility. 184 | // If the request's post body is null, then the assumption is that the request is 185 | // GET. Otherwise, it is assumed that the request is a POST. 186 | byte[] postBody = request.getPostBody(); 187 | if (postBody != null) { 188 | // Prepare output. There is no need to set Content-Length explicitly, 189 | // since this is handled by HttpURLConnection using the size of the prepared 190 | // output stream. 191 | connection.setDoOutput(true); 192 | connection.setRequestMethod("POST"); 193 | connection.addRequestProperty(HEADER_CONTENT_TYPE, 194 | request.getPostBodyContentType()); 195 | DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 196 | out.write(postBody); 197 | out.close(); 198 | } 199 | break; 200 | case Method.GET: 201 | // Not necessary to set the request method because connection defaults to GET but 202 | // being explicit here. 203 | connection.setRequestMethod("GET"); 204 | break; 205 | case Method.DELETE: 206 | connection.setRequestMethod("DELETE"); 207 | break; 208 | case Method.POST: 209 | connection.setRequestMethod("POST"); 210 | addBodyIfExists(connection, request); 211 | break; 212 | case Method.PUT: 213 | connection.setRequestMethod("PUT"); 214 | addBodyIfExists(connection, request); 215 | break; 216 | case Method.HEAD: 217 | connection.setRequestMethod("HEAD"); 218 | break; 219 | case Method.OPTIONS: 220 | connection.setRequestMethod("OPTIONS"); 221 | break; 222 | case Method.TRACE: 223 | connection.setRequestMethod("TRACE"); 224 | break; 225 | case Method.PATCH: 226 | connection.setRequestMethod("PATCH"); 227 | addBodyIfExists(connection, request); 228 | break; 229 | default: 230 | throw new IllegalStateException("Unknown method type."); 231 | } 232 | } 233 | 234 | private static void addBodyIfExists(HttpURLConnection connection, Request request) 235 | throws IOException, AuthFailureError { 236 | byte[] body = request.getBody(); 237 | if (body != null) { 238 | connection.setDoOutput(true); 239 | connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); 240 | DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 241 | out.write(body); 242 | out.close(); 243 | } 244 | } 245 | } 246 | -------------------------------------------------------------------------------- /volley-android-6.0.1_25/src/main/java/com/android/volley/toolbox/ImageRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.volley.toolbox; 18 | 19 | import android.graphics.Bitmap; 20 | import android.graphics.Bitmap.Config; 21 | import android.graphics.BitmapFactory; 22 | import android.widget.ImageView.ScaleType; 23 | 24 | import com.android.volley.DefaultRetryPolicy; 25 | import com.android.volley.NetworkResponse; 26 | import com.android.volley.ParseError; 27 | import com.android.volley.Request; 28 | import com.android.volley.Response; 29 | import com.android.volley.VolleyLog; 30 | 31 | /** 32 | * A canned request for getting an image at a given URL and calling 33 | * back with a decoded Bitmap. 34 | */ 35 | public class ImageRequest extends Request { 36 | /** Socket timeout in milliseconds for image requests */ 37 | public static final int DEFAULT_IMAGE_TIMEOUT_MS = 1000; 38 | 39 | /** Default number of retries for image requests */ 40 | public static final int DEFAULT_IMAGE_MAX_RETRIES = 2; 41 | 42 | /** Default backoff multiplier for image requests */ 43 | public static final float DEFAULT_IMAGE_BACKOFF_MULT = 2f; 44 | 45 | private final Response.Listener mListener; 46 | private final Config mDecodeConfig; 47 | private final int mMaxWidth; 48 | private final int mMaxHeight; 49 | private ScaleType mScaleType; 50 | 51 | /** Decoding lock so that we don't decode more than one image at a time (to avoid OOM's) */ 52 | private static final Object sDecodeLock = new Object(); 53 | 54 | /** 55 | * Creates a new image request, decoding to a maximum specified width and 56 | * height. If both width and height are zero, the image will be decoded to 57 | * its natural size. If one of the two is nonzero, that dimension will be 58 | * clamped and the other one will be set to preserve the image's aspect 59 | * ratio. If both width and height are nonzero, the image will be decoded to 60 | * be fit in the rectangle of dimensions width x height while keeping its 61 | * aspect ratio. 62 | * 63 | * @param url URL of the image 64 | * @param listener Listener to receive the decoded bitmap 65 | * @param maxWidth Maximum width to decode this bitmap to, or zero for none 66 | * @param maxHeight Maximum height to decode this bitmap to, or zero for 67 | * none 68 | * @param scaleType The ImageViews ScaleType used to calculate the needed image size. 69 | * @param decodeConfig Format to decode the bitmap to 70 | * @param errorListener Error listener, or null to ignore errors 71 | */ 72 | public ImageRequest(String url, Response.Listener listener, int maxWidth, int maxHeight, 73 | ScaleType scaleType, Config decodeConfig, Response.ErrorListener errorListener) { 74 | super(Method.GET, url, errorListener); 75 | setRetryPolicy(new DefaultRetryPolicy(DEFAULT_IMAGE_TIMEOUT_MS, DEFAULT_IMAGE_MAX_RETRIES, 76 | DEFAULT_IMAGE_BACKOFF_MULT)); 77 | mListener = listener; 78 | mDecodeConfig = decodeConfig; 79 | mMaxWidth = maxWidth; 80 | mMaxHeight = maxHeight; 81 | mScaleType = scaleType; 82 | } 83 | 84 | /** 85 | * For API compatibility with the pre-ScaleType variant of the constructor. Equivalent to 86 | * the normal constructor with {@code ScaleType.CENTER_INSIDE}. 87 | */ 88 | @Deprecated 89 | public ImageRequest(String url, Response.Listener listener, int maxWidth, int maxHeight, 90 | Config decodeConfig, Response.ErrorListener errorListener) { 91 | this(url, listener, maxWidth, maxHeight, 92 | ScaleType.CENTER_INSIDE, decodeConfig, errorListener); 93 | } 94 | @Override 95 | public Priority getPriority() { 96 | return Priority.LOW; 97 | } 98 | 99 | /** 100 | * Scales one side of a rectangle to fit aspect ratio. 101 | * 102 | * @param maxPrimary Maximum size of the primary dimension (i.e. width for 103 | * max width), or zero to maintain aspect ratio with secondary 104 | * dimension 105 | * @param maxSecondary Maximum size of the secondary dimension, or zero to 106 | * maintain aspect ratio with primary dimension 107 | * @param actualPrimary Actual size of the primary dimension 108 | * @param actualSecondary Actual size of the secondary dimension 109 | * @param scaleType The ScaleType used to calculate the needed image size. 110 | */ 111 | private static int getResizedDimension(int maxPrimary, int maxSecondary, int actualPrimary, 112 | int actualSecondary, ScaleType scaleType) { 113 | 114 | // If no dominant value at all, just return the actual. 115 | if ((maxPrimary == 0) && (maxSecondary == 0)) { 116 | return actualPrimary; 117 | } 118 | 119 | // If ScaleType.FIT_XY fill the whole rectangle, ignore ratio. 120 | if (scaleType == ScaleType.FIT_XY) { 121 | if (maxPrimary == 0) { 122 | return actualPrimary; 123 | } 124 | return maxPrimary; 125 | } 126 | 127 | // If primary is unspecified, scale primary to match secondary's scaling ratio. 128 | if (maxPrimary == 0) { 129 | double ratio = (double) maxSecondary / (double) actualSecondary; 130 | return (int) (actualPrimary * ratio); 131 | } 132 | 133 | if (maxSecondary == 0) { 134 | return maxPrimary; 135 | } 136 | 137 | double ratio = (double) actualSecondary / (double) actualPrimary; 138 | int resized = maxPrimary; 139 | 140 | // If ScaleType.CENTER_CROP fill the whole rectangle, preserve aspect ratio. 141 | if (scaleType == ScaleType.CENTER_CROP) { 142 | if ((resized * ratio) < maxSecondary) { 143 | resized = (int) (maxSecondary / ratio); 144 | } 145 | return resized; 146 | } 147 | 148 | if ((resized * ratio) > maxSecondary) { 149 | resized = (int) (maxSecondary / ratio); 150 | } 151 | return resized; 152 | } 153 | 154 | @Override 155 | protected Response parseNetworkResponse(NetworkResponse response) { 156 | // Serialize all decode on a global lock to reduce concurrent heap usage. 157 | synchronized (sDecodeLock) { 158 | try { 159 | return doParse(response); 160 | } catch (OutOfMemoryError e) { 161 | VolleyLog.e("Caught OOM for %d byte image, url=%s", response.data.length, getUrl()); 162 | return Response.error(new ParseError(e)); 163 | } 164 | } 165 | } 166 | 167 | /** 168 | * The real guts of parseNetworkResponse. Broken out for readability. 169 | */ 170 | private Response doParse(NetworkResponse response) { 171 | byte[] data = response.data; 172 | BitmapFactory.Options decodeOptions = new BitmapFactory.Options(); 173 | Bitmap bitmap = null; 174 | if (mMaxWidth == 0 && mMaxHeight == 0) { 175 | decodeOptions.inPreferredConfig = mDecodeConfig; 176 | bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); 177 | } else { 178 | // If we have to resize this image, first get the natural bounds. 179 | decodeOptions.inJustDecodeBounds = true; 180 | BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); 181 | int actualWidth = decodeOptions.outWidth; 182 | int actualHeight = decodeOptions.outHeight; 183 | 184 | // Then compute the dimensions we would ideally like to decode to. 185 | int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight, 186 | actualWidth, actualHeight, mScaleType); 187 | int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth, 188 | actualHeight, actualWidth, mScaleType); 189 | 190 | // Decode to the nearest power of two scaling factor. 191 | decodeOptions.inJustDecodeBounds = false; 192 | // TODO(ficus): Do we need this or is it okay since API 8 doesn't support it? 193 | // decodeOptions.inPreferQualityOverSpeed = PREFER_QUALITY_OVER_SPEED; 194 | decodeOptions.inSampleSize = 195 | findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight); 196 | Bitmap tempBitmap = 197 | BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions); 198 | 199 | // If necessary, scale down to the maximal acceptable size. 200 | if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth || 201 | tempBitmap.getHeight() > desiredHeight)) { 202 | bitmap = Bitmap.createScaledBitmap(tempBitmap, 203 | desiredWidth, desiredHeight, true); 204 | tempBitmap.recycle(); 205 | } else { 206 | bitmap = tempBitmap; 207 | } 208 | } 209 | 210 | if (bitmap == null) { 211 | return Response.error(new ParseError(response)); 212 | } else { 213 | return Response.success(bitmap, HttpHeaderParser.parseCacheHeaders(response)); 214 | } 215 | } 216 | 217 | @Override 218 | protected void deliverResponse(Bitmap response) { 219 | mListener.onResponse(response); 220 | } 221 | 222 | /** 223 | * Returns the largest power-of-two divisor for use in downscaling a bitmap 224 | * that will not result in the scaling past the desired dimensions. 225 | * 226 | * @param actualWidth Actual width of the bitmap 227 | * @param actualHeight Actual height of the bitmap 228 | * @param desiredWidth Desired width of the bitmap 229 | * @param desiredHeight Desired height of the bitmap 230 | */ 231 | // Visible for testing. 232 | static int findBestSampleSize( 233 | int actualWidth, int actualHeight, int desiredWidth, int desiredHeight) { 234 | double wr = (double) actualWidth / desiredWidth; 235 | double hr = (double) actualHeight / desiredHeight; 236 | double ratio = Math.min(wr, hr); 237 | float n = 1.0f; 238 | while ((n * 2) <= ratio) { 239 | n *= 2; 240 | } 241 | 242 | return (int) n; 243 | } 244 | } 245 | --------------------------------------------------------------------------------