├── .gitignore
├── .idea
├── compiler.xml
├── copyright
│ └── profiles_settings.xml
├── encodings.xml
├── gradle.xml
├── misc.xml
├── modules.xml
└── runConfigurations.xml
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── zx
│ │ └── okhttp3
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── zx
│ │ │ └── okhttp3
│ │ │ ├── MainActivity.java
│ │ │ └── OKHttpUtils.java
│ └── res
│ │ ├── layout
│ │ └── activity_main.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── zx
│ └── okhttp3
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── library
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── zx
│ │ └── uploadlibrary
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── zx
│ │ │ └── uploadlibrary
│ │ │ ├── helper
│ │ │ └── ProgressHelper.java
│ │ │ ├── listener
│ │ │ ├── ProgressListener.java
│ │ │ └── impl
│ │ │ │ ├── UIProgressListener.java
│ │ │ │ ├── handler
│ │ │ │ └── ProgressHandler.java
│ │ │ │ └── model
│ │ │ │ └── ProgressModel.java
│ │ │ ├── progress
│ │ │ ├── ProgressRequestBody.java
│ │ │ └── ProgressResponseBody.java
│ │ │ └── utils
│ │ │ └── OKHttpUtils.java
│ └── res
│ │ └── values
│ │ └── strings.xml
│ └── test
│ └── java
│ └── com
│ └── zx
│ └── uploadlibrary
│ └── ExampleUnitTest.java
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
19 |
20 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | 1.8
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | #### 一、简介
2 | v1.01版本
3 | 对OKHttp的封装,可实现多文件上传(带进度值)、表单提交到服务器;下载文件保存到到本地(带进度值)。
4 | 可以在文件上传/下载时,在开始、结束、进度回调3个方法中自定义内容。
5 |
6 | #### 二、使用步骤:
7 |
8 | **1、Gradle添加如下2个依赖**
9 | ```
10 | allprojects {
11 | repositories {
12 | ...
13 | maven { url 'https://jitpack.io' }
14 | }
15 | }
16 |
17 | dependencies {
18 | compile 'com.github.zhouxu88:OkHttp3_MultiFile:v1.0'
19 | }
20 | ```
21 |
22 | **2、多文件上传的调用**
23 | ```
24 | //多文件上传(带进度)
25 | private void upload() {
26 | //这个是非ui线程回调,不可直接操作UI
27 | final ProgressListener progressListener = new ProgressListener() {
28 | @Override
29 | public void onProgress(long bytesWrite, long contentLength, boolean done) {
30 | Log.i("TAG", "bytesWrite:" + bytesWrite);
31 | Log.i("TAG", "contentLength" + contentLength);
32 | Log.i("TAG", (100 * bytesWrite) / contentLength + " % done ");
33 | Log.i("TAG", "done:" + done);
34 | Log.i("TAG", "================================");
35 | }
36 | };
37 |
38 |
39 | //这个是ui线程回调,可直接操作UI
40 | UIProgressListener uiProgressRequestListener = new UIProgressListener() {
41 | @Override
42 | public void onUIProgress(long bytesWrite, long contentLength, boolean done) {
43 | Log.i("TAG", "bytesWrite:" + bytesWrite);
44 | Log.i("TAG", "contentLength" + contentLength);
45 | Log.i("TAG", (100 * bytesWrite) / contentLength + " % done ");
46 | Log.i("TAG", "done:" + done);
47 | Log.i("TAG", "================================");
48 | //ui层回调,设置当前上传的进度值
49 | int progress = (int) ((100 * bytesWrite) / contentLength);
50 | uploadProgress.setProgress(progress);
51 | uploadTV.setText("上传进度值:" + progress + "%");
52 | }
53 |
54 | //上传开始
55 | @Override
56 | public void onUIStart(long bytesWrite, long contentLength, boolean done) {
57 | super.onUIStart(bytesWrite, contentLength, done);
58 | Toast.makeText(getApplicationContext(),"开始上传",Toast.LENGTH_SHORT).show();
59 | }
60 |
61 | //上传结束
62 | @Override
63 | public void onUIFinish(long bytesWrite, long contentLength, boolean done) {
64 | super.onUIFinish(bytesWrite, contentLength, done);
65 | //uploadProgress.setVisibility(View.GONE); //设置进度条不可见
66 | Toast.makeText(getApplicationContext(),"上传成功",Toast.LENGTH_SHORT).show();
67 |
68 | }
69 | };
70 |
71 |
72 | //开始Post请求,上传文件
73 | OKHttpUtils.doPostRequest(POST_FILE_URL, initUploadFile(), uiProgressRequestListener, new Callback() {
74 | @Override
75 | public void onFailure(Call call, final IOException e) {
76 | Log.i("TAG", "error------> "+e.getMessage());
77 | runOnUiThread(new Runnable() {
78 | @Override
79 | public void run() {
80 | Toast.makeText(MainActivity.this, "上传失败"+e.getMessage(), Toast.LENGTH_SHORT).show();
81 | }
82 | });
83 |
84 | }
85 |
86 | @Override
87 | public void onResponse(Call call, Response response) throws IOException {
88 | Log.i("TAG", "success---->"+response.body().string());
89 | }
90 | });
91 |
92 | }
93 |
94 | //初始化上传文件的数据
95 | private List initUploadFile(){
96 | List fileNames = new ArrayList<>();
97 | fileNames.add(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
98 | + File.separator + "test.txt"); //txt文件
99 | fileNames.add(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
100 | + File.separator + "bell.png"); //图片
101 | fileNames.add(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
102 | + File.separator + "kobe.mp4"); //视频
103 | fileNames.add(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)
104 | + File.separator + "xinnian.mp3"); //音乐
105 | return fileNames;
106 | }
107 |
108 | ```
109 |
110 | **3、文件下载的调用**
111 | ```
112 | //文件下载
113 | private void download() {
114 | //这个是非ui线程回调,不可直接操作UI
115 | final ProgressListener progressResponseListener = new ProgressListener() {
116 | @Override
117 | public void onProgress(long bytesRead, long contentLength, boolean done) {
118 | Log.i("TAG", "bytesRead:" + bytesRead);
119 | Log.i("TAG", "contentLength:" + contentLength);
120 | Log.i("TAG", "done:" + done);
121 | if (contentLength != -1) {
122 | //长度未知的情况下回返回-1
123 | Log.i("TAG", (100 * bytesRead) / contentLength + "% done");
124 | }
125 | Log.i("TAG", "================================");
126 | }
127 | };
128 |
129 |
130 | //这个是ui线程回调,可直接操作UI
131 | final UIProgressListener uiProgressResponseListener = new UIProgressListener() {
132 | @Override
133 | public void onUIProgress(long bytesRead, long contentLength, boolean done) {
134 | Log.i("TAG", "bytesRead:" + bytesRead);
135 | Log.i("TAG", "contentLength:" + contentLength);
136 | Log.i("TAG", "done:" + done);
137 | if (contentLength != -1) {
138 | //长度未知的情况下回返回-1
139 | Log.i("TAG", (100 * bytesRead) / contentLength + "% done");
140 | }
141 | Log.i("TAG", "================================");
142 | //ui层回调,设置下载进度
143 | int progress = (int) ((100 * bytesRead) / contentLength);
144 | downloadProgress.setProgress(progress);
145 | downloadTv.setText("下载进度:" + progress +"%");
146 | }
147 |
148 | @Override
149 | public void onUIStart(long bytesRead, long contentLength, boolean done) {
150 | super.onUIStart(bytesRead, contentLength, done);
151 | Toast.makeText(getApplicationContext(),"开始下载",Toast.LENGTH_SHORT).show();
152 | }
153 |
154 | @Override
155 | public void onUIFinish(long bytesRead, long contentLength, boolean done) {
156 | super.onUIFinish(bytesRead, contentLength, done);
157 | Toast.makeText(getApplicationContext(),"下载完成",Toast.LENGTH_SHORT).show();
158 | }
159 | };
160 |
161 | //开启文件下载
162 | OKHttpUtils.downloadAndSaveFile(this,DOWNLOAD_TEST_URL,STORE_DOWNLOAD_FILE_PATH,uiProgressResponseListener);
163 |
164 | }
165 | ```
166 |
167 | **备注**
168 | > 文件上传、下载中的UIProgressListener 实现的3个方法onUIProgress()、onUIStart()、onUIFinish()的内容都可以根据项目需求自定义
169 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 24
5 | buildToolsVersion "24.0.3"
6 | defaultConfig {
7 | applicationId "com.zx.okhttp3"
8 | minSdkVersion 17
9 | targetSdkVersion 24
10 | versionCode 1
11 | versionName "1.0"
12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
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 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
25 | exclude group: 'com.android.support', module: 'support-annotations'
26 | })
27 | compile 'com.android.support:appcompat-v7:24.2.1'
28 | testCompile 'junit:junit:4.12'
29 | compile 'com.squareup.okhttp3:okhttp:3.5.0'
30 | compile 'com.google.code.gson:gson:2.8.0'
31 | compile project(':library')
32 | }
33 |
--------------------------------------------------------------------------------
/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 E:\SDK\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/androidTest/java/com/zx/okhttp3/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.zx.okhttp3;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.zx.okhttp3", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zx/okhttp3/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.zx.okhttp3;
2 |
3 | import android.os.Bundle;
4 | import android.os.Environment;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.util.Log;
7 | import android.view.View;
8 | import android.widget.ProgressBar;
9 | import android.widget.TextView;
10 | import android.widget.Toast;
11 |
12 | import com.zx.uploadlibrary.listener.ProgressListener;
13 | import com.zx.uploadlibrary.listener.impl.UIProgressListener;
14 | import com.zx.uploadlibrary.utils.OKHttpUtils;
15 |
16 | import java.io.File;
17 | import java.io.IOException;
18 | import java.util.ArrayList;
19 | import java.util.List;
20 |
21 | import okhttp3.Call;
22 | import okhttp3.Callback;
23 | import okhttp3.Response;
24 |
25 | public class MainActivity extends AppCompatActivity{
26 |
27 |
28 |
29 | //上传文件到服务器的地址(使用的时候替换成自己的服务器地址)
30 | private static final String POST_FILE_URL = "http://192.168.1.3:8080/UploadFileDemo/MutilUploadServlet";
31 | //下载文件的地址
32 | private static final String DOWNLOAD_TEST_URL = "http://oh0vbg8a6.bkt.clouddn.com/app-debug.apk";
33 |
34 | //下载的文件的存储路径
35 | private static final String STORE_DOWNLOAD_FILE_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator +"download2.apk";
36 | private ProgressBar uploadProgress, downloadProgress;
37 | private TextView uploadTV,downloadTv;
38 |
39 |
40 |
41 | @Override
42 | protected void onCreate(Bundle savedInstanceState) {
43 | super.onCreate(savedInstanceState);
44 | setContentView(R.layout.activity_main);
45 | initView();
46 | }
47 |
48 | //初始化View
49 | private void initView() {
50 | uploadProgress = (ProgressBar) findViewById(R.id.upload_progress);
51 | downloadProgress = (ProgressBar) findViewById(R.id.download_progress);
52 | uploadTV = (TextView) findViewById(R.id.tv_upload_progress);
53 | downloadTv = (TextView) findViewById(R.id.tv_download_progress);
54 | findViewById(R.id.upload).setOnClickListener(new View.OnClickListener() {
55 | @Override
56 | public void onClick(View v) {
57 | upload();
58 | }
59 | });
60 | findViewById(R.id.download).setOnClickListener(new View.OnClickListener() {
61 | @Override
62 | public void onClick(View v) {
63 | download();
64 | }
65 | });
66 | }
67 |
68 | //多文件上传(带进度)
69 | private void upload() {
70 | //这个是非ui线程回调,不可直接操作UI
71 | final ProgressListener progressListener = new ProgressListener() {
72 | @Override
73 | public void onProgress(long bytesWrite, long contentLength, boolean done) {
74 | Log.i("TAG", "bytesWrite:" + bytesWrite);
75 | Log.i("TAG", "contentLength" + contentLength);
76 | Log.i("TAG", (100 * bytesWrite) / contentLength + " % done ");
77 | Log.i("TAG", "done:" + done);
78 | Log.i("TAG", "================================");
79 | }
80 | };
81 |
82 |
83 | //这个是ui线程回调,可直接操作UI
84 | UIProgressListener uiProgressRequestListener = new UIProgressListener() {
85 | @Override
86 | public void onUIProgress(long bytesWrite, long contentLength, boolean done) {
87 | Log.i("TAG", "bytesWrite:" + bytesWrite);
88 | Log.i("TAG", "contentLength" + contentLength);
89 | Log.i("TAG", (100 * bytesWrite) / contentLength + " % done ");
90 | Log.i("TAG", "done:" + done);
91 | Log.i("TAG", "================================");
92 | //ui层回调,设置当前上传的进度值
93 | int progress = (int) ((100 * bytesWrite) / contentLength);
94 | uploadProgress.setProgress(progress);
95 | uploadTV.setText("上传进度值:" + progress + "%");
96 | }
97 |
98 | //上传开始
99 | @Override
100 | public void onUIStart(long bytesWrite, long contentLength, boolean done) {
101 | super.onUIStart(bytesWrite, contentLength, done);
102 | Toast.makeText(getApplicationContext(),"开始上传",Toast.LENGTH_SHORT).show();
103 | }
104 |
105 | //上传结束
106 | @Override
107 | public void onUIFinish(long bytesWrite, long contentLength, boolean done) {
108 | super.onUIFinish(bytesWrite, contentLength, done);
109 | //uploadProgress.setVisibility(View.GONE); //设置进度条不可见
110 | Toast.makeText(getApplicationContext(),"上传成功",Toast.LENGTH_SHORT).show();
111 |
112 | }
113 | };
114 |
115 |
116 | //开始Post请求,上传文件
117 | OKHttpUtils.doPostRequest(POST_FILE_URL, initUploadFile(), uiProgressRequestListener, new Callback() {
118 | @Override
119 | public void onFailure(Call call, final IOException e) {
120 | Log.i("TAG", "error------> "+e.getMessage());
121 | runOnUiThread(new Runnable() {
122 | @Override
123 | public void run() {
124 | Toast.makeText(MainActivity.this, "上传失败"+e.getMessage(), Toast.LENGTH_SHORT).show();
125 | }
126 | });
127 |
128 | }
129 |
130 | @Override
131 | public void onResponse(Call call, Response response) throws IOException {
132 | Log.i("TAG", "success---->"+response.body().string());
133 | }
134 | });
135 |
136 | }
137 |
138 |
139 | //文件下载
140 | private void download() {
141 | //这个是非ui线程回调,不可直接操作UI
142 | final ProgressListener progressResponseListener = new ProgressListener() {
143 | @Override
144 | public void onProgress(long bytesRead, long contentLength, boolean done) {
145 | Log.i("TAG", "bytesRead:" + bytesRead);
146 | Log.i("TAG", "contentLength:" + contentLength);
147 | Log.i("TAG", "done:" + done);
148 | if (contentLength != -1) {
149 | //长度未知的情况下回返回-1
150 | Log.i("TAG", (100 * bytesRead) / contentLength + "% done");
151 | }
152 | Log.i("TAG", "================================");
153 | }
154 | };
155 |
156 |
157 | //这个是ui线程回调,可直接操作UI
158 | final UIProgressListener uiProgressResponseListener = new UIProgressListener() {
159 | @Override
160 | public void onUIProgress(long bytesRead, long contentLength, boolean done) {
161 | Log.i("TAG", "bytesRead:" + bytesRead);
162 | Log.i("TAG", "contentLength:" + contentLength);
163 | Log.i("TAG", "done:" + done);
164 | if (contentLength != -1) {
165 | //长度未知的情况下回返回-1
166 | Log.i("TAG", (100 * bytesRead) / contentLength + "% done");
167 | }
168 | Log.i("TAG", "================================");
169 | //ui层回调,设置下载进度
170 | int progress = (int) ((100 * bytesRead) / contentLength);
171 | downloadProgress.setProgress(progress);
172 | downloadTv.setText("下载进度:" + progress +"%");
173 | }
174 |
175 | @Override
176 | public void onUIStart(long bytesRead, long contentLength, boolean done) {
177 | super.onUIStart(bytesRead, contentLength, done);
178 | Toast.makeText(getApplicationContext(),"开始下载",Toast.LENGTH_SHORT).show();
179 | }
180 |
181 | @Override
182 | public void onUIFinish(long bytesRead, long contentLength, boolean done) {
183 | super.onUIFinish(bytesRead, contentLength, done);
184 | Toast.makeText(getApplicationContext(),"下载完成",Toast.LENGTH_SHORT).show();
185 | }
186 | };
187 |
188 | //开启文件下载
189 | OKHttpUtils.downloadAndSaveFile(this,DOWNLOAD_TEST_URL,STORE_DOWNLOAD_FILE_PATH,uiProgressResponseListener);
190 |
191 | }
192 |
193 | //初始化上传文件的数据
194 | private List initUploadFile(){
195 | List fileNames = new ArrayList<>();
196 | fileNames.add(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
197 | + File.separator + "test.txt"); //txt文件
198 | fileNames.add(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
199 | + File.separator + "bell.png"); //图片
200 | fileNames.add(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
201 | + File.separator + "kobe.mp4"); //视频
202 | fileNames.add(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)
203 | + File.separator + "xinnian.mp3"); //音乐
204 | return fileNames;
205 | }
206 |
207 | }
208 |
--------------------------------------------------------------------------------
/app/src/main/java/com/zx/okhttp3/OKHttpUtils.java:
--------------------------------------------------------------------------------
1 | package com.zx.okhttp3;
2 |
3 |
4 | import com.zx.uploadlibrary.helper.ProgressHelper;
5 | import com.zx.uploadlibrary.listener.ProgressListener;
6 |
7 | import java.io.File;
8 | import java.io.IOException;
9 | import java.net.FileNameMap;
10 | import java.net.URLConnection;
11 | import java.util.List;
12 | import java.util.concurrent.TimeUnit;
13 |
14 | import okhttp3.Call;
15 | import okhttp3.Callback;
16 | import okhttp3.MediaType;
17 | import okhttp3.MultipartBody;
18 | import okhttp3.OkHttpClient;
19 | import okhttp3.Request;
20 | import okhttp3.RequestBody;
21 | import okhttp3.Response;
22 |
23 | /**
24 | * Created by 周旭 on 2017/1/18.
25 | * OKHttp工具类(上传,下载文件)
26 | */
27 |
28 | public class OKHttpUtils {
29 |
30 | private static OkHttpClient client;
31 |
32 | /**
33 | * 创建一个OkHttpClient的对象的单例
34 | * @return
35 | */
36 | private synchronized static OkHttpClient getOkHttpClientInstance() {
37 | if (client == null) {
38 | OkHttpClient.Builder builder = new OkHttpClient.Builder()
39 | //设置连接超时等属性,不设置可能会报异常
40 | .connectTimeout(120, TimeUnit.SECONDS)
41 | .readTimeout(120, TimeUnit.SECONDS)
42 | .writeTimeout(120, TimeUnit.SECONDS);
43 |
44 | client = builder.build();
45 | }
46 | return client;
47 | }
48 |
49 |
50 | /**
51 | * 获取文件MimeType
52 | *
53 | * @param filename
54 | * @return
55 | */
56 | private static String getMimeType(String filename) {
57 | FileNameMap filenameMap = URLConnection.getFileNameMap();
58 | String contentType = filenameMap.getContentTypeFor(filename);
59 | if (contentType == null) {
60 | contentType = "application/octet-stream"; //* exe,所有的可执行程序
61 | }
62 | return contentType;
63 | }
64 |
65 |
66 | /**
67 | * 获得Request实例(不带进度)
68 | * @param url
69 | * @return
70 | */
71 | private static Request getRequest(String url, List fileNames) {
72 | Request.Builder builder = new Request.Builder();
73 | builder.url(url)
74 | .post(getRequestBody(fileNames));
75 | return builder.build();
76 | }
77 |
78 |
79 | /**
80 | * 获得Request实例(带进度)
81 | * @param url
82 | * @return
83 | */
84 | private static Request getRequest(String url, List fileNames, ProgressListener uiProgressRequestListener) {
85 | Request.Builder builder = new Request.Builder();
86 | builder.url(url)
87 | .post(ProgressHelper.addProgressRequestListener(
88 | OKHttpUtils.getRequestBody(fileNames),
89 | uiProgressRequestListener));
90 | return builder.build();
91 | }
92 |
93 |
94 | /**
95 | * 通过上传的文件的完整路径生成RequestBody
96 | * @param fileNames 完整的文件路径
97 | * @return
98 | */
99 | private static RequestBody getRequestBody(List fileNames) {
100 | //创建MultipartBody.Builder,用于添加请求的数据
101 | MultipartBody.Builder builder = new MultipartBody.Builder();
102 | for (int i = 0; i < fileNames.size(); i++) { //对文件进行遍历
103 | File file = new File(fileNames.get(i)); //生成文件
104 | //根据文件的后缀名,获得文件类型
105 | String fileType = getMimeType(file.getName());
106 | builder.addFormDataPart( //给Builder添加上传的文件
107 | "image", //请求的名字
108 | file.getName(), //文件的文字,服务器端用来解析的
109 | RequestBody.create(MediaType.parse(fileType), file) //创建RequestBody,把上传的文件放入
110 | );
111 | }
112 | return builder.build(); //根据Builder创建请求
113 | }
114 |
115 | /**
116 | * 根据url,发送异步Post请求(带进度)
117 | * @param url 提交到服务器的地址
118 | * @param fileNames 完整的上传的文件的路径名
119 | * @param callback OkHttp的回调接口
120 | */
121 | public static void doPostRequest(String url, List fileNames, ProgressListener uiProgressRequestListener, Callback callback) {
122 | Call call = getOkHttpClientInstance().newCall(getRequest(url,fileNames,uiProgressRequestListener));
123 | call.enqueue(callback);
124 | }
125 |
126 | /**
127 | * 根据url,发送异步Post请求(不带进度)
128 | * @param url 提交到服务器的地址
129 | * @param fileNames 完整的上传的文件的路径名
130 | * @param callback OkHttp的回调接口
131 | */
132 | public static void doPostRequest(String url, List fileNames, Callback callback) {
133 | Call call = getOkHttpClientInstance().newCall(getRequest(url,fileNames));
134 | call.enqueue(callback);
135 | }
136 |
137 | //获取字符串
138 | public static String getString(Response response) throws IOException {
139 | if (response != null && response.isSuccessful()) {
140 | return response.body().string();
141 | }
142 | return null;
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
17 |
18 |
25 |
26 |
31 |
32 |
41 |
42 |
49 |
50 |
55 |
56 |
57 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhouxu88/OkHttp3_MultiFile/87c1cea7a8a871c7f3cae2209fcaa4d8680662a9/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhouxu88/OkHttp3_MultiFile/87c1cea7a8a871c7f3cae2209fcaa4d8680662a9/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhouxu88/OkHttp3_MultiFile/87c1cea7a8a871c7f3cae2209fcaa4d8680662a9/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhouxu88/OkHttp3_MultiFile/87c1cea7a8a871c7f3cae2209fcaa4d8680662a9/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhouxu88/OkHttp3_MultiFile/87c1cea7a8a871c7f3cae2209fcaa4d8680662a9/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | OkHttp3
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/zx/okhttp3/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.zx.okhttp3;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.2.2'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | jcenter()
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zhouxu88/OkHttp3_MultiFile/87c1cea7a8a871c7f3cae2209fcaa4d8680662a9/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/library/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/library/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 24
5 | buildToolsVersion "24.0.3"
6 |
7 | defaultConfig {
8 | minSdkVersion 17
9 | targetSdkVersion 24
10 | versionCode 1
11 | versionName "1.0"
12 |
13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14 |
15 | }
16 | buildTypes {
17 | release {
18 | minifyEnabled false
19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20 | }
21 | }
22 | }
23 |
24 | dependencies {
25 | compile fileTree(include: ['*.jar'], dir: 'libs')
26 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
27 | exclude group: 'com.android.support', module: 'support-annotations'
28 | })
29 | compile 'com.android.support:appcompat-v7:24.2.1'
30 | testCompile 'junit:junit:4.12'
31 | compile 'com.squareup.okhttp3:okhttp:3.5.0'
32 | }
33 |
--------------------------------------------------------------------------------
/library/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 E:\SDK\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 |
--------------------------------------------------------------------------------
/library/src/androidTest/java/com/zx/uploadlibrary/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.zx.uploadlibrary;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.zx.uploadlibrary.test", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/library/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/library/src/main/java/com/zx/uploadlibrary/helper/ProgressHelper.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2015 ZhangQu Li
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.zx.uploadlibrary.helper;
17 |
18 | import com.zx.uploadlibrary.listener.ProgressListener;
19 | import com.zx.uploadlibrary.progress.ProgressRequestBody;
20 | import com.zx.uploadlibrary.progress.ProgressResponseBody;
21 |
22 | import java.io.IOException;
23 |
24 | import okhttp3.Interceptor;
25 | import okhttp3.OkHttpClient;
26 | import okhttp3.RequestBody;
27 | import okhttp3.Response;
28 |
29 |
30 | /**
31 | * 进度回调辅助类
32 | */
33 | public class ProgressHelper {
34 | /**
35 | * 包装OkHttpClient,用于下载文件的回调
36 | *
37 | * @param client 待包装的OkHttpClient
38 | * @param progressListener 进度回调接口
39 | * @param storePath 下载的文件的存储路径
40 | * @return 包装后的OkHttpClient,使用clone方法返回
41 | */
42 | public static OkHttpClient addProgressResponseListener(OkHttpClient client, final ProgressListener progressListener, String storePath) {
43 | Interceptor interceptor = new Interceptor() {
44 | @Override
45 | public Response intercept(Chain chain) throws IOException {
46 | //拦截
47 | Response originalResponse = chain.proceed(chain.request());
48 | //包装响应体并返回
49 | return originalResponse.newBuilder()
50 | .body(new ProgressResponseBody(originalResponse.body(), progressListener))
51 | .build();
52 | }
53 | };
54 | return client.newBuilder()
55 | .addInterceptor(interceptor)
56 | .build();
57 | }
58 |
59 | /**
60 | * 包装请求体用于上传文件的回调
61 | *
62 | * @param requestBody 请求体RequestBody
63 | * @param progressRequestListener 进度回调接口
64 | * @return 包装后的进度回调请求体
65 | */
66 | public static ProgressRequestBody addProgressRequestListener(RequestBody requestBody, ProgressListener progressRequestListener) {
67 | //包装请求体
68 | return new ProgressRequestBody(requestBody, progressRequestListener);
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/library/src/main/java/com/zx/uploadlibrary/listener/ProgressListener.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2015 ZhangQu Li
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.zx.uploadlibrary.listener;
17 |
18 | /**
19 | * 进度回调接口,比如用于文件上传与下载
20 | * User:lizhangqu(513163535@qq.com)
21 | * Date:2015-09-02
22 | * Time: 17:16
23 | */
24 | public interface ProgressListener {
25 | void onProgress(long currentBytes, long contentLength, boolean done);
26 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/zx/uploadlibrary/listener/impl/UIProgressListener.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2015 ZhangQu Li
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.zx.uploadlibrary.listener.impl;
17 |
18 | import android.os.Handler;
19 | import android.os.Message;
20 |
21 | import com.zx.uploadlibrary.listener.ProgressListener;
22 | import com.zx.uploadlibrary.listener.impl.handler.ProgressHandler;
23 | import com.zx.uploadlibrary.listener.impl.model.ProgressModel;
24 |
25 |
26 | /**
27 | * 请求体回调实现类,用于UI层回调
28 | */
29 | public abstract class UIProgressListener implements ProgressListener {
30 | private boolean isFirst = false;
31 |
32 | //处理UI层的Handler子类
33 | private static class UIHandler extends ProgressHandler {
34 | public UIHandler(UIProgressListener uiProgressListener) {
35 | super(uiProgressListener);
36 | }
37 |
38 | @Override
39 | public void start(UIProgressListener uiProgressListener, long currentBytes, long contentLength, boolean done) {
40 | if (uiProgressListener!=null) {
41 | uiProgressListener.onUIStart(currentBytes, contentLength, done);
42 | }
43 | }
44 |
45 | @Override
46 | public void progress(UIProgressListener uiProgressListener, long currentBytes, long contentLength, boolean done) {
47 | if (uiProgressListener!=null){
48 | uiProgressListener.onUIProgress(currentBytes, contentLength, done);
49 | }
50 | }
51 |
52 | @Override
53 | public void finish(UIProgressListener uiProgressListener, long currentBytes, long contentLength, boolean done) {
54 | if (uiProgressListener!=null){
55 | uiProgressListener.onUIFinish(currentBytes, contentLength,done);
56 | }
57 | }
58 | }
59 |
60 | //主线程Handler
61 | private final Handler mHandler = new UIHandler(this);
62 |
63 | @Override
64 | public void onProgress(long bytesWrite, long contentLength, boolean done) {
65 | //如果是第一次,发送消息
66 | if (!isFirst) {
67 | isFirst = true;
68 | Message start = Message.obtain();
69 | start.obj = new ProgressModel(bytesWrite, contentLength, done);
70 | start.what = ProgressHandler.START;
71 | mHandler.sendMessage(start);
72 | }
73 |
74 | //通过Handler发送进度消息
75 | Message message = Message.obtain();
76 | message.obj = new ProgressModel(bytesWrite, contentLength, done);
77 | message.what = ProgressHandler.UPDATE;
78 | mHandler.sendMessage(message);
79 |
80 | if(done) {
81 | Message finish = Message.obtain();
82 | finish.obj = new ProgressModel(bytesWrite, contentLength, done);
83 | finish.what = ProgressHandler.FINISH;
84 | mHandler.sendMessage(finish);
85 | }
86 | }
87 |
88 | /**
89 | * UI层回调抽象方法
90 | *
91 | * @param currentBytes 当前的字节长度
92 | * @param contentLength 总字节长度
93 | * @param done 是否写入完成
94 | */
95 | public abstract void onUIProgress(long currentBytes, long contentLength, boolean done);
96 |
97 | /**
98 | * UI层开始请求回调方法
99 | * @param currentBytes 当前的字节长度
100 | * @param contentLength 总字节长度
101 | * @param done 是否写入完成
102 | */
103 | public void onUIStart(long currentBytes, long contentLength, boolean done) {
104 |
105 | }
106 |
107 | /**
108 | * UI层结束请求回调方法
109 | * @param currentBytes 当前的字节长度
110 | * @param contentLength 总字节长度
111 | * @param done 是否写入完成
112 | */
113 | public void onUIFinish(long currentBytes, long contentLength, boolean done) {
114 |
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/library/src/main/java/com/zx/uploadlibrary/listener/impl/handler/ProgressHandler.java:
--------------------------------------------------------------------------------
1 | package com.zx.uploadlibrary.listener.impl.handler;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 | import android.os.Message;
6 |
7 | import com.zx.uploadlibrary.listener.impl.UIProgressListener;
8 | import com.zx.uploadlibrary.listener.impl.model.ProgressModel;
9 |
10 | import java.lang.ref.WeakReference;
11 |
12 |
13 |
14 | public abstract class ProgressHandler extends Handler {
15 | public static final int UPDATE = 0x01;
16 | public static final int START = 0x02;
17 | public static final int FINISH = 0x03;
18 | //弱引用
19 | private final WeakReference mUIProgressListenerWeakReference;
20 |
21 | public ProgressHandler(UIProgressListener uiProgressListener) {
22 | super(Looper.getMainLooper());
23 | mUIProgressListenerWeakReference = new WeakReference(uiProgressListener);
24 | }
25 |
26 | @Override
27 | public void handleMessage(Message msg) {
28 | switch (msg.what) {
29 | case UPDATE: {
30 | UIProgressListener uiProgessListener = mUIProgressListenerWeakReference.get();
31 | if (uiProgessListener != null) {
32 | //获得进度实体类
33 | ProgressModel progressModel = (ProgressModel) msg.obj;
34 | //回调抽象方法
35 | progress(uiProgessListener, progressModel.getCurrentBytes(), progressModel.getContentLength(), progressModel.isDone());
36 | }
37 | break;
38 | }
39 | case START: {
40 | UIProgressListener uiProgressListener = mUIProgressListenerWeakReference.get();
41 | if (uiProgressListener != null) {
42 | //获得进度实体类
43 | ProgressModel progressModel = (ProgressModel) msg.obj;
44 | //回调抽象方法
45 | start(uiProgressListener, progressModel.getCurrentBytes(), progressModel.getContentLength(), progressModel.isDone());
46 |
47 | }
48 | break;
49 | }
50 | case FINISH: {
51 | UIProgressListener uiProgressListener = mUIProgressListenerWeakReference.get();
52 | if (uiProgressListener != null) {
53 | //获得进度实体类
54 | ProgressModel progressModel = (ProgressModel) msg.obj;
55 | //回调抽象方法
56 | finish(uiProgressListener, progressModel.getCurrentBytes(), progressModel.getContentLength(), progressModel.isDone());
57 | }
58 | break;
59 | }
60 | default:
61 | super.handleMessage(msg);
62 | break;
63 | }
64 | }
65 |
66 | public abstract void start(UIProgressListener uiProgressListener,long currentBytes, long contentLength, boolean done);
67 | public abstract void progress(UIProgressListener uiProgressListener,long currentBytes, long contentLength, boolean done);
68 | public abstract void finish(UIProgressListener uiProgressListener,long currentBytes, long contentLength, boolean done);
69 | }
70 |
--------------------------------------------------------------------------------
/library/src/main/java/com/zx/uploadlibrary/listener/impl/model/ProgressModel.java:
--------------------------------------------------------------------------------
1 |
2 | package com.zx.uploadlibrary.listener.impl.model;
3 |
4 | import java.io.Serializable;
5 |
6 | /**
7 | * UI进度回调实体类
8 | */
9 | public class ProgressModel implements Serializable {
10 | //当前读取字节长度
11 | private long currentBytes;
12 | //总字节长度
13 | private long contentLength;
14 | //是否读取完成
15 | private boolean done;
16 |
17 | public ProgressModel(long currentBytes, long contentLength, boolean done) {
18 | this.currentBytes = currentBytes;
19 | this.contentLength = contentLength;
20 | this.done = done;
21 | }
22 |
23 | public long getCurrentBytes() {
24 | return currentBytes;
25 | }
26 |
27 | public void setCurrentBytes(long currentBytes) {
28 | this.currentBytes = currentBytes;
29 | }
30 |
31 | public long getContentLength() {
32 | return contentLength;
33 | }
34 |
35 | public void setContentLength(long contentLength) {
36 | this.contentLength = contentLength;
37 | }
38 |
39 | public boolean isDone() {
40 | return done;
41 | }
42 |
43 | public void setDone(boolean done) {
44 | this.done = done;
45 | }
46 |
47 | @Override
48 | public String toString() {
49 | return "ProgressModel{" +
50 | "currentBytes=" + currentBytes +
51 | ", contentLength=" + contentLength +
52 | ", done=" + done +
53 | '}';
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/library/src/main/java/com/zx/uploadlibrary/progress/ProgressRequestBody.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2015 ZhangQu Li
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.zx.uploadlibrary.progress;
17 |
18 |
19 | import com.zx.uploadlibrary.listener.ProgressListener;
20 |
21 | import java.io.IOException;
22 |
23 | import okhttp3.MediaType;
24 | import okhttp3.RequestBody;
25 | import okio.Buffer;
26 | import okio.BufferedSink;
27 | import okio.ForwardingSink;
28 | import okio.Okio;
29 | import okio.Sink;
30 |
31 | /**
32 | * 包装的请求体,处理进度
33 | */
34 | public class ProgressRequestBody extends RequestBody {
35 | //实际的待包装请求体
36 | private final RequestBody requestBody;
37 | //进度回调接口
38 | private final ProgressListener progressListener;
39 | //包装完成的BufferedSink
40 | private BufferedSink bufferedSink;
41 |
42 | /**
43 | * 构造函数,赋值
44 | * @param requestBody 待包装的请求体
45 | * @param progressListener 回调接口
46 | */
47 | public ProgressRequestBody(RequestBody requestBody, ProgressListener progressListener) {
48 | this.requestBody = requestBody;
49 | this.progressListener = progressListener;
50 | }
51 |
52 | /**
53 | * 重写调用实际的响应体的contentType
54 | * @return MediaType
55 | */
56 | @Override
57 | public MediaType contentType() {
58 | return requestBody.contentType();
59 | }
60 |
61 | /**
62 | * 重写调用实际的响应体的contentLength
63 | * @return contentLength
64 | * @throws IOException 异常
65 | */
66 | @Override
67 | public long contentLength() throws IOException {
68 | return requestBody.contentLength();
69 | }
70 |
71 | /**
72 | * 重写进行写入
73 | * @param sink BufferedSink
74 | * @throws IOException 异常
75 | */
76 | @Override
77 | public void writeTo(BufferedSink sink) throws IOException {
78 | if (bufferedSink == null) {
79 | //包装
80 | bufferedSink = Okio.buffer(sink(sink));
81 | }
82 | //写入
83 | requestBody.writeTo(bufferedSink);
84 | //必须调用flush,否则最后一部分数据可能不会被写入
85 | bufferedSink.flush();
86 |
87 | }
88 |
89 | /**
90 | * 写入,回调进度接口
91 | * @param sink Sink
92 | * @return Sink
93 | */
94 | private Sink sink(Sink sink) {
95 | return new ForwardingSink(sink) {
96 |
97 | //当前写入字节数
98 | long bytesWritten = 0L;
99 | //总字节长度,避免多次调用contentLength()方法
100 | long contentLength = 0L;
101 |
102 | @Override
103 | public void write(Buffer source, long byteCount) throws IOException {
104 | super.write(source, byteCount);
105 | if (contentLength == 0) {
106 | //获得contentLength的值,后续不再调用
107 | contentLength = contentLength();
108 | }
109 | //增加当前写入的字节数
110 | bytesWritten += byteCount;
111 | //回调
112 | if (progressListener!=null) {
113 | progressListener.onProgress(bytesWritten, contentLength, bytesWritten == contentLength);
114 | }
115 | }
116 | };
117 | }
118 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/zx/uploadlibrary/progress/ProgressResponseBody.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2015 ZhangQu Li
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.zx.uploadlibrary.progress;
17 |
18 |
19 | import com.zx.uploadlibrary.listener.ProgressListener;
20 |
21 | import java.io.IOException;
22 |
23 | import okhttp3.MediaType;
24 | import okhttp3.ResponseBody;
25 | import okio.Buffer;
26 | import okio.BufferedSource;
27 | import okio.ForwardingSource;
28 | import okio.Okio;
29 | import okio.Source;
30 |
31 |
32 | /**
33 | * 包装的响体,处理进度
34 | */
35 | public class ProgressResponseBody extends ResponseBody {
36 | //实际的待包装响应体
37 | private final ResponseBody responseBody;
38 | //进度回调接口
39 | private final ProgressListener progressListener;
40 | //包装完成的BufferedSource
41 | private BufferedSource bufferedSource;
42 |
43 | /**
44 | * 构造函数,赋值
45 | * @param responseBody 待包装的响应体
46 | * @param progressListener 回调接口
47 | */
48 | public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) {
49 | this.responseBody = responseBody;
50 | this.progressListener = progressListener;
51 | }
52 |
53 |
54 | /**
55 | * 重写调用实际的响应体的contentType
56 | * @return MediaType
57 | */
58 | @Override public MediaType contentType() {
59 | return responseBody.contentType();
60 | }
61 |
62 | /**
63 | * 重写调用实际的响应体的contentLength
64 | * @return contentLength
65 | * @throws IOException 异常
66 | */
67 | @Override public long contentLength() {
68 | return responseBody.contentLength();
69 | }
70 |
71 | /**
72 | * 重写进行包装source
73 | * @return BufferedSource
74 | * @throws IOException 异常
75 | */
76 | @Override public BufferedSource source() {
77 | if (bufferedSource == null) {
78 | //包装
79 | bufferedSource = Okio.buffer(source(responseBody.source()));
80 | }
81 | return bufferedSource;
82 | }
83 |
84 | /**
85 | * 读取,回调进度接口
86 | * @param source Source
87 | * @return Source
88 | */
89 | private Source source(Source source) {
90 |
91 | return new ForwardingSource(source) {
92 | //当前读取字节数
93 | long totalBytesRead = 0L;
94 | @Override public long read(Buffer sink, long byteCount) throws IOException {
95 | long bytesRead = super.read(sink, byteCount);
96 | //增加当前读取的字节数,如果读取完成了bytesRead会返回-1
97 | totalBytesRead += bytesRead != -1 ? bytesRead : 0;
98 | //回调,如果contentLength()不知道长度,会返回-1
99 | if (progressListener!=null) {
100 | progressListener.onProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
101 | }
102 | return bytesRead;
103 | }
104 | };
105 | }
106 | }
--------------------------------------------------------------------------------
/library/src/main/java/com/zx/uploadlibrary/utils/OKHttpUtils.java:
--------------------------------------------------------------------------------
1 | package com.zx.uploadlibrary.utils;
2 |
3 |
4 | import android.app.Activity;
5 | import android.util.Log;
6 | import android.widget.Toast;
7 |
8 | import com.zx.uploadlibrary.helper.ProgressHelper;
9 | import com.zx.uploadlibrary.listener.ProgressListener;
10 | import com.zx.uploadlibrary.listener.impl.UIProgressListener;
11 |
12 | import java.io.BufferedInputStream;
13 | import java.io.File;
14 | import java.io.FileOutputStream;
15 | import java.io.IOException;
16 | import java.io.InputStream;
17 | import java.net.FileNameMap;
18 | import java.net.URLConnection;
19 | import java.util.HashMap;
20 | import java.util.List;
21 | import java.util.concurrent.TimeUnit;
22 |
23 | import okhttp3.Call;
24 | import okhttp3.Callback;
25 | import okhttp3.FormBody;
26 | import okhttp3.MediaType;
27 | import okhttp3.MultipartBody;
28 | import okhttp3.OkHttpClient;
29 | import okhttp3.Request;
30 | import okhttp3.RequestBody;
31 | import okhttp3.Response;
32 | import okhttp3.ResponseBody;
33 |
34 | /**
35 | * Created by 周旭 on 2017/1/18.
36 | * OKHttp工具类(上传,下载文件)
37 | */
38 |
39 | public class OKHttpUtils {
40 |
41 | private static OkHttpClient client;
42 |
43 | /**
44 | * 创建一个OkHttpClient的对象的单例
45 | *
46 | * @return
47 | */
48 | public synchronized static OkHttpClient getOkHttpClientInstance() {
49 | if (client == null) {
50 | OkHttpClient.Builder builder = new OkHttpClient.Builder()
51 | //设置连接超时等属性,不设置可能会报异常
52 | .connectTimeout(120, TimeUnit.SECONDS)
53 | .readTimeout(120, TimeUnit.SECONDS)
54 | .writeTimeout(120, TimeUnit.SECONDS);
55 |
56 | client = builder.build();
57 | }
58 | return client;
59 | }
60 |
61 |
62 | /**
63 | * 获取文件MimeType
64 | *
65 | * @param filename 文件名
66 | * @return
67 | */
68 | private static String getMimeType(String filename) {
69 | FileNameMap filenameMap = URLConnection.getFileNameMap();
70 | String contentType = filenameMap.getContentTypeFor(filename);
71 | if (contentType == null) {
72 | contentType = "application/octet-stream"; //* exe,所有的可执行程序
73 | }
74 | return contentType;
75 | }
76 |
77 | /**
78 | * 上传文件
79 | * 获得Request实例(不带进度)
80 | *
81 | * @param url 上传文件到服务器的地址
82 | * @param fileNames 完整的文件名(带完整路径)
83 | * @return
84 | */
85 | private static Request getRequest(String url, List fileNames) {
86 | Request.Builder builder = new Request.Builder();
87 | builder.url(url)
88 | .post(getRequestBody(fileNames))
89 | .tag(url) //设置请求的标记,可在取消时使用
90 | ;
91 | return builder.build();
92 | }
93 |
94 | /**
95 | * 上传文件
96 | * 获得Request实例(带进度)
97 | *
98 | * @param url 上传文件到服务器的地址
99 | * @param fileNames 完整的文件名(带完整路径)
100 | * @param uiProgressRequestListener 上传进度的监听器
101 | * @return
102 | */
103 | private static Request getRequest(String url, List fileNames, ProgressListener uiProgressRequestListener) {
104 | Request.Builder builder = new Request.Builder();
105 | builder.url(url)
106 | .post(ProgressHelper.addProgressRequestListener(
107 | OKHttpUtils.getRequestBody(fileNames),
108 | uiProgressRequestListener));
109 | return builder.build();
110 | }
111 |
112 | /**
113 | * 通过Url地址和表单的键值对来创建Request实例
114 | *
115 | * @param url 上传表单数据到服务器的地址
116 | * @param map 由提交的表单的每一项组成的HashMap
117 | * (如用户名,key:username,value:zhangsan)
118 | * @return
119 | */
120 | private static Request getRequest(String url, HashMap map) {
121 | Request.Builder builder = new Request.Builder();
122 | builder.url(url)
123 | .post(getRequestBody(map))
124 | .tag(url) //设置请求的标记,可在取消时使用
125 | ;
126 | return builder.build();
127 | }
128 |
129 | /**
130 | * 通过Url地址和表单的键值对来创建Request实例
131 | *
132 | * @param url 上传表单数据到服务器的地址
133 | * @param map 由提交的表单的每一项组成的HashMap
134 | * (如用户名,key:username,value:zhangsan)
135 | * @param fileNames 完整的文件路径名
136 | * @return
137 | */
138 | private static Request getRequest(String url, HashMap map, List fileNames) {
139 | Request.Builder builder = new Request.Builder();
140 | builder.url(url)
141 | .post(getRequestBody(map, fileNames))
142 | .tag(url) //设置请求的标记,可在取消时使用
143 | ;
144 | return builder.build();
145 | }
146 |
147 | /**
148 | * 通过下载的URL地址构建equest实例
149 | *
150 | * @param downloadUrl 文件下载的地址
151 | * @return
152 | */
153 | private static Request getRequest(String downloadUrl) {
154 | Request.Builder builder = new Request.Builder();
155 | builder.url(downloadUrl).tag(downloadUrl);
156 | return builder.build();
157 | }
158 |
159 | /**
160 | * 通过键值对(表单中的name-value)创建RequestBody
161 | *
162 | * @param map 由提交的表单的每一项组成的HashMap
163 | * (如用户名,key:username,value:zhangsan)
164 | * @return
165 | */
166 | private static RequestBody getRequestBody(HashMap map) {
167 | FormBody.Builder builder = new FormBody.Builder();
168 | for (HashMap.Entry entry : map.entrySet()) {
169 | builder.add(entry.getKey(), entry.getValue());
170 | }
171 | return builder.build();
172 | }
173 |
174 | /**
175 | * 根据表单的键值对和上传的文件生成RequestBody
176 | *
177 | * @param map 由提交的表单的每一项组成的HashMap
178 | * (如用户名,key:username,value:zhangsan)
179 | * @param fileNames 完整的文件路径名
180 | * @return
181 | */
182 | private static RequestBody getRequestBody(HashMap map, List fileNames) {
183 | MultipartBody.Builder builder = new MultipartBody.Builder(); //创建MultipartBody.Builder,用于添加请求的数据
184 | for (HashMap.Entry entry : map.entrySet()) { //对键值对进行遍历
185 | builder.addFormDataPart(entry.getKey(), entry.getValue()); //把键值对添加到Builder中
186 | }
187 | for (int i = 0; i < fileNames.size(); i++) { //对文件进行遍历
188 | File file = new File(fileNames.get(i)); //生成文件
189 | String fileType = getMimeType(file.getName()); //根据文件的后缀名,获得文件类型
190 | builder.addFormDataPart( //给Builder添加上传的文件
191 | "image", //请求的名字
192 | file.getName(), //文件的文字,服务器端用来解析的
193 | RequestBody.create(MediaType.parse(fileType), file) //创建RequestBody,把上传的文件放入
194 | );
195 | }
196 | return builder.build(); //根据Builder创建请求
197 | }
198 |
199 |
200 | /**
201 | * 通过上传的文件的完整路径生成RequestBody
202 | *
203 | * @param fileNames 完整的文件路径
204 | * @return
205 | */
206 | private static RequestBody getRequestBody(List fileNames) {
207 | //创建MultipartBody.Builder,用于添加请求的数据
208 | MultipartBody.Builder builder = new MultipartBody.Builder();
209 | for (int i = 0; i < fileNames.size(); i++) { //对文件进行遍历
210 | File file = new File(fileNames.get(i)); //生成文件
211 | //根据文件的后缀名,获得文件类型
212 | String fileType = getMimeType(file.getName());
213 | builder.addFormDataPart( //给Builder添加上传的文件
214 | "image", //请求的名字
215 | file.getName(), //文件的文字,服务器端用来解析的
216 | RequestBody.create(MediaType.parse(fileType), file) //创建RequestBody,把上传的文件放入
217 | );
218 | }
219 | return builder.build(); //根据Builder创建请求
220 | }
221 |
222 | /**
223 | * 只上传文件
224 | * 根据url,发送异步Post请求(带进度)
225 | *
226 | * @param url 提交到服务器的地址
227 | * @param fileNames 完整的上传的文件的路径名
228 | * @param uiProgressRequestListener 上传进度的监听器
229 | * @param callback OkHttp的回调接口
230 | */
231 | public static void doPostRequest(String url, List fileNames, ProgressListener uiProgressRequestListener, Callback callback) {
232 | Call call = getOkHttpClientInstance().newCall(getRequest(url, fileNames, uiProgressRequestListener));
233 | call.enqueue(callback);
234 | }
235 |
236 | /**
237 | * 只上传文件
238 | * 根据url,发送异步Post请求(不带进度)
239 | *
240 | * @param url 提交到服务器的地址
241 | * @param fileNames 完整的上传的文件的路径名
242 | * @param callback OkHttp的回调接口
243 | */
244 | public static void doPostRequest(String url, List fileNames, Callback callback) {
245 | Call call = getOkHttpClientInstance().newCall(getRequest(url, fileNames));
246 | call.enqueue(callback);
247 | }
248 |
249 | /**
250 | * 只提交表单
251 | * 根据url和键值对,发送异步Post请求
252 | *
253 | * @param url 提交到服务器的地址
254 | * @param map 提交的表单的每一项组成的HashMap
255 | * (如用户名,key:username,value:zhangsan)
256 | * @param callback OkHttp的回调接口
257 | */
258 | public static void doPostRequest(String url, HashMap map, Callback callback) {
259 | Call call = getOkHttpClientInstance().newCall(getRequest(url, map));
260 | call.enqueue(callback);
261 | }
262 |
263 |
264 | /**
265 | * 可同时提交表单,和多文件
266 | * 根据url和键值对,发送异步Post请求
267 | *
268 | * @param url 提交到服务器的地址
269 | * @param map 提交的表单的每一项组成的HashMap
270 | * (如用户名,key:username,value:zhangsan)
271 | * @param fileNames 完整的上传的文件的路径名
272 | * @param callback OkHttp的回调接口
273 | */
274 | public static void doPostRequest(String url, HashMap map, List fileNames, Callback callback) {
275 | Call call = getOkHttpClientInstance().newCall(getRequest(url, map, fileNames));
276 | call.enqueue(callback);
277 | }
278 |
279 |
280 | /**
281 | * 文件下载(带进度)
282 | *
283 | * @param downloadUrl 文件的下载地址
284 | * @param savePath 下载后的文件的保存路径
285 | * @param uiProgressResponseListener 下载进度的监听器
286 | */
287 | public static void downloadAndSaveFile(final Activity activity, String downloadUrl, final String savePath, UIProgressListener uiProgressResponseListener) {
288 | //包装Response使其支持进度回调
289 | ProgressHelper.addProgressResponseListener(OKHttpUtils.getOkHttpClientInstance(), uiProgressResponseListener, savePath)
290 | .newCall(getRequest(downloadUrl))
291 | .enqueue(new Callback() {
292 | @Override
293 | public void onFailure(Call call, final IOException e) {
294 | Log.i("TAG", "下载错误: " + e.getMessage());
295 | activity.runOnUiThread(new Runnable() {
296 | @Override
297 | public void run() {
298 | Toast.makeText(activity, "下载错误"+e.getMessage(), Toast.LENGTH_SHORT).show();
299 | }
300 | });
301 | }
302 |
303 | @Override
304 | public void onResponse(Call call, Response response) throws IOException {
305 | Log.i("TAG", "服务器响应成功");
306 | //在本地保存文件
307 | OKHttpUtils.saveDownloadFile(response, savePath);
308 | }
309 | });
310 | }
311 |
312 | //在本地保存下载的文件
313 | private static void saveDownloadFile(Response response, String savePath) throws IOException {
314 | InputStream inputStream = getInputStreamFromResponse(response);
315 | BufferedInputStream bis = new BufferedInputStream(inputStream);
316 | FileOutputStream fos = new FileOutputStream(savePath);
317 | byte[] data = new byte[10 * 1024];
318 | int len;
319 | while ((len = bis.read(data)) != -1) {
320 | fos.write(data, 0, len);
321 | }
322 | Log.i("TAG", "保存文件"+savePath+"成功");
323 | fos.flush();
324 | fos.close();
325 | bis.close();
326 | }
327 |
328 | //获取字符串
329 | public static String getString(Response response) throws IOException {
330 | if (response != null && response.isSuccessful()) {
331 | return response.body().string();
332 | }
333 | return null;
334 | }
335 |
336 |
337 | /**
338 | * 根据响应获得字节数组
339 | *
340 | * @param response
341 | * @return
342 | * @throws IOException
343 | */
344 | public static byte[] getBytesFromResponse(Response response) throws IOException {
345 | if (response != null && response.isSuccessful()) {
346 | ResponseBody responseBody = response.body();
347 | if (responseBody != null) {
348 | return responseBody.bytes();
349 | }
350 | }
351 | return null;
352 | }
353 |
354 |
355 | /**
356 | * 根据响应获得输入流
357 | *
358 | * @param response
359 | * @return
360 | * @throws IOException
361 | */
362 | public static InputStream getInputStreamFromResponse(Response response) throws IOException {
363 | if (response != null && response.isSuccessful()) {
364 | ResponseBody responseBody = response.body();
365 | if (responseBody != null) {
366 | return responseBody.byteStream();
367 | }
368 | }
369 | return null;
370 | }
371 |
372 |
373 | /**
374 | * 取消所有为tag的Call
375 | *
376 | * @param tag 请求的标记
377 | */
378 | public static void cancelCallsWithTag(Object tag) {
379 |
380 | if (tag == null) {
381 | return;
382 | }
383 |
384 | synchronized (client.dispatcher().getClass()) {
385 | for (Call call : client.dispatcher().queuedCalls()) {
386 | if (tag.equals(call.request().tag())) call.cancel();
387 | }
388 |
389 | for (Call call : client.dispatcher().runningCalls()) {
390 | if (tag.equals(call.request().tag())) call.cancel();
391 | }
392 | }
393 | }
394 | }
395 |
--------------------------------------------------------------------------------
/library/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | UploadLibrary
3 |
4 |
--------------------------------------------------------------------------------
/library/src/test/java/com/zx/uploadlibrary/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.zx.uploadlibrary;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':library'
2 |
--------------------------------------------------------------------------------