├── .gitignore
├── .idea
├── caches
│ └── build_file_checksums.ser
├── codeStyles
│ └── Project.xml
├── compiler.xml
├── dbnavigator.xml
├── gradle.xml
├── jarRepositories.xml
├── misc.xml
├── modules.xml
└── vcs.xml
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── assets
│ └── test.txt
│ ├── java
│ └── com
│ │ └── ansen
│ │ └── okhttp
│ │ └── test
│ │ ├── activity
│ │ └── MainActivity.java
│ │ ├── app
│ │ └── MyApplication.java
│ │ └── entity
│ │ ├── BaseProtocol.java
│ │ └── User.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
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── okhttpencapsulation
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── ansen
│ │ └── http
│ │ ├── entity
│ │ └── HttpConfig.java
│ │ ├── net
│ │ ├── HTTPCaller.java
│ │ ├── Header.java
│ │ ├── HttpResponseHandler.java
│ │ ├── NameValuePair.java
│ │ └── RequestDataCallback.java
│ │ └── util
│ │ └── Util.java
│ └── res
│ └── values
│ └── strings.xml
└── 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/caches/build_file_checksums.ser:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ansen666/OkHttpEncapsulation/d475510220f89419aa25e055d920625413a61193/.idea/caches/build_file_checksums.ser
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.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 | xmlns:android
38 |
39 | ^$
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 | xmlns:.*
49 |
50 | ^$
51 |
52 |
53 | BY_NAME
54 |
55 |
56 |
57 |
58 |
59 |
60 | .*:id
61 |
62 | http://schemas.android.com/apk/res/android
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 | .*:name
72 |
73 | http://schemas.android.com/apk/res/android
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 | name
83 |
84 | ^$
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 | style
94 |
95 | ^$
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 | .*
105 |
106 | ^$
107 |
108 |
109 | BY_NAME
110 |
111 |
112 |
113 |
114 |
115 |
116 | .*
117 |
118 | http://schemas.android.com/apk/res/android
119 |
120 |
121 | ANDROID_ATTRIBUTE_ORDER
122 |
123 |
124 |
125 |
126 |
127 |
128 | .*
129 |
130 | .*
131 |
132 |
133 | BY_NAME
134 |
135 |
136 |
137 |
138 |
139 |
140 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/dbnavigator.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 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 |
206 |
207 |
208 |
209 |
210 |
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 |
230 |
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 |
258 |
259 |
260 |
261 |
262 |
263 |
264 |
265 |
266 |
267 |
268 |
269 |
270 |
271 |
272 |
273 |
274 |
275 |
276 |
277 |
278 |
279 |
280 |
281 |
282 |
283 |
284 |
285 |
286 |
287 |
288 |
289 |
290 |
291 |
292 |
293 |
294 |
295 |
296 |
297 |
298 |
299 |
300 |
301 |
302 |
303 |
304 |
305 |
306 |
307 |
308 |
309 |
310 |
311 |
312 |
313 |
314 |
315 |
316 |
317 |
318 |
319 |
320 |
321 |
322 |
323 |
324 |
325 |
326 |
327 |
328 |
329 |
330 |
331 |
332 |
333 |
334 |
335 |
336 |
337 |
338 |
339 |
340 |
341 |
342 |
343 |
344 |
345 |
346 |
347 |
348 |
349 |
350 |
351 |
352 |
353 |
354 |
355 |
356 |
357 |
358 |
359 |
360 |
361 |
362 |
363 |
364 |
365 |
366 |
367 |
368 |
369 |
370 |
371 |
372 |
373 |
374 |
375 |
376 |
377 |
378 |
379 |
380 |
381 |
382 |
383 |
384 |
385 |
386 |
387 |
388 |
389 |
390 |
391 |
392 |
393 |
394 |
395 |
396 |
397 |
398 |
399 |
400 |
401 |
402 |
403 |
404 |
405 |
406 |
407 |
408 |
409 |
410 |
411 |
412 |
413 |
414 |
415 |
416 |
417 |
418 |
419 |
420 |
421 |
422 |
423 |
424 |
425 |
426 |
427 |
428 |
429 |
430 |
431 |
432 |
433 |
434 |
435 |
436 |
437 |
438 |
439 |
440 |
441 |
442 |
443 |
444 |
445 |
446 |
447 |
448 |
449 |
450 |
451 |
452 |
453 |
454 |
455 |
456 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
20 |
21 |
--------------------------------------------------------------------------------
/.idea/jarRepositories.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 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | 1.8
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ### 前言
2 | http请求基本上每一个app都会使用,进行好的封装提供Activity调用是非常有必要的,并且当我们切换http请求库的时候也只会修改封装的地方,而不需要修改Activity代码。最近比较火的http请求库就属[OkHttp](https://github.com/square/okhttp)了,这里我们对[OkHttp](https://github.com/square/okhttp)的get请求、post请求、上传文件进行了封装。
3 |
4 | ### 封装的目的
5 | - 封装基本的公共方法给外部调用。get请求,Post请求- ,PostFile,downloadFile。简化代码。
6 | - 官方建议OkHttpClient实例只new一次。
7 | - 如果同一时间访问同一个api多次,那我们默认情况只会保留最后一个请求。这个调用的可以也可以通过参数控制。
8 | - 如果用户连接Http代理了,就不让访问,防止用户通过抓包工具看我们的接口数据。这个也可以在初始化的时候通过改变HttpConfig的agent属性控制。
9 | - 每个接口都要带上的参数应该封装起来,例如app版本号,设备号,登录之后的用户token,这些参数可能每次请求都要带上。当然我们需要的时候也可以对公共参数进行修改。
10 | - 把返回的json字符串转成对象再回调回来。当然你想要byte数组也可以。只需要重写RequestDataCallback接口的不同方法。
11 | - 我们访问服务器用的是异步请求,不可能每个调用的地方拿到数据还要通过handler来刷新ui,底层直接封装了一个handler统一处理。
12 | - 上传文件跟下载文件支持进度回调。
13 |
14 | ### 使用
15 | #### 1.依赖
16 | 如果是android studio开发支持在线依赖:
17 | ```
18 | compile 'com.ansen.http:okhttpencapsulation:1.0.5'
19 | ```
20 |
21 | 如果是eclipse那你先把ide切换到android studio吧。。。不闲麻烦的话也可以把源码module的源码copy出来,反正也就几个类。
22 |
23 | #### 2.初始化HTTPCaller类
24 | 初始化的工作可以放Application,新建MyApplication类继承Application。初始化的时候通过HttpConfig设置一些参数,也可以添加公共参数。
25 | ```
26 | public class MyApplication extends Application{
27 | @Override
28 | public void onCreate() {
29 | super.onCreate();
30 |
31 | HttpConfig httpConfig=new HttpConfig();
32 | httpConfig.setAgent(true);//有代理的情况能不能访问
33 | httpConfig.setDebug(true);//是否debug模式 如果是debug模式打印log
34 | httpConfig.setTagName("ansen");//打印log的tagname
35 |
36 | //可以添加一些公共字段 每个接口都会带上
37 | httpConfig.addCommonField("pf","android");
38 | httpConfig.addCommonField("version_code","1");
39 |
40 | //初始化HTTPCaller类
41 | HTTPCaller.getInstance().setHttpConfig(httpConfig);
42 | }
43 | }
44 | ```
45 |
46 | 因为自定义Application,需要给AndroidManifest.xml文件application标签中的android:name属性赋值,指定自己重写的MyApplication。
47 |
48 | #### 发送get请求
49 | 发送get请求就一行代码。
50 | ```
51 | HTTPCaller.getInstance().get(User.class, "http://139.196.35.30:8080/OkHttpTest/getUserInfo.do?per=123", null, requestDataCallback);
52 | ```
53 |
54 | #### 请求回调
55 | http请求回调接口,无论成功或者失败都会回调。因为是测试所以都用在这个接口来回调,在真实的企业开发中,不同的请求用不同的回调。
56 | ```
57 | private RequestDataCallback requestDataCallback = new RequestDataCallback() {
58 | @Override
59 | public void dataCallback(User user) {
60 | if(user==null){
61 | Log.i("ansen", "请求失败");
62 | }else{
63 | Log.i("ansen", "获取用户信息:" + user.toString());
64 | }
65 |
66 | }
67 | };
68 | ```
69 |
70 | #### 发送post请求
71 | post请求参数不是跟在url后面的,所以需要把请求参数放到集合里面。因为登录接口也是返回的用户信息,所以可以跟get请求用同一回调。
72 | ```
73 | List postParam = new ArrayList<>();
74 | postParam.add(new NameValuePair("username","ansen"));
75 | postParam.add(new NameValuePair("password","123"));
76 | HTTPCaller.getInstance().post(User.class, "http://139.196.35.30:8080/OkHttpTest/login.do", null, postParam, requestDataCallback);
77 | ```
78 |
79 | #### 上传文件
80 | ##### 1.上传文件不带回调进度
81 | ```
82 | updaloadFile(null);
83 | ```
84 |
85 | ##### 2.上传文件回调上传进度
86 | ```
87 | updaloadFile(new ProgressUIListener(){
88 | @Override
89 | public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
90 | Log.i("ansen","numBytes:"+numBytes+" totalBytes:"+totalBytes+" percent:"+percent+" speed:"+speed);
91 | }
92 | });
93 | ```
94 |
95 | 上传文件跟其他表单参数不一样的地方就是new NameValuePair对象的时候需要传入三个参数,最后一个参数需要设置成true。
96 | ```
97 | private void updaloadFile(ProgressUIListener progressUIListener){
98 | List postParam = new ArrayList<>();
99 | postParam.add(new NameValuePair("username", "ansen"));
100 | postParam.add(new NameValuePair("password", "123"));
101 | String filePath=copyFile();//复制一份文件到sdcard上,并且获取文件路径
102 | postParam.add(new NameValuePair("upload_file",filePath,true));
103 | if(progressUIListener==null){//上传文件没有回调进度条
104 | HTTPCaller.getInstance().postFile(User.class, "http://139.196.35.30:8080/OkHttpTest/uploadFile.do", null, postParam, requestDataCallback);
105 | }else{//上传文件并且回调上传进度
106 | HTTPCaller.getInstance().postFile(User.class, "http://139.196.35.30:8080/OkHttpTest/uploadFile.do", null, postParam, requestDataCallback,progressUIListener);
107 | }
108 | }
109 | ```
110 |
111 | #### 上传文件(传入byte数组)
112 | ```
113 | byte[] bytes=getUploadFileBytes();//获取文件内容存入byte数组
114 | HTTPCaller.getInstance().postFile(User.class, "http://139.196.35.30:8080/OkHttpTest/uploadFile.do", null, "upload_file","test.txt",bytes,requestDataCallback);
115 | ```
116 |
117 | #### 上传文件(传入byte数组)&&回调上传进度
118 | ```
119 | byte[] bytes=getUploadFileBytes();//获取文件内容存入byte数组
120 | HTTPCaller.getInstance().postFile(User.class, "http://139.196.35.30:8080/OkHttpTest/uploadFile.do", null, "upload_file", "test.txt", bytes, requestDataCallback, new ProgressUIListener() {
121 | @Override
122 | public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
123 | Log.i("ansen","upload file content numBytes:"+numBytes+" totalBytes:"+totalBytes+" percent:"+percent+" speed:"+speed);
124 | }
125 | });
126 | ```
127 |
128 | #### 下载文件&&回调下载进度
129 | ```
130 | String saveFilePath=Environment.getExternalStorageDirectory() + "/test/test222.txt";
131 | HTTPCaller.getInstance().downloadFile("http://139.196.35.30:8080/OkHttpTest/upload/test.txt",saveFilePath,null,new ProgressUIListener(){
132 | @Override
133 | public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
134 | Log.i("ansen","dowload file content numBytes:"+numBytes+" totalBytes:"+totalBytes+" percent:"+percent+" speed:"+speed);
135 | }
136 | });
137 | ```
138 |
139 | #### 修改公共参数
140 | ```
141 | HTTPCaller.getInstance().updateCommonField("version_code","2");//更新公共字段版本号的值
142 | ```
143 |
144 | ### 关于这几个测试接口的服务器
145 | [想看服务器源码点这里](https://github.com/ansen666/OkHttpTest)
146 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 29
5 | buildToolsVersion "29.0.3"
6 |
7 | defaultConfig {
8 | applicationId "com.ansen.okhttp.test"
9 | minSdkVersion 19
10 | targetSdkVersion 29
11 | versionCode 1
12 | versionName "1.0"
13 | testInstrumentationRunner "androidx.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 | implementation fileTree(dir: 'libs', include: ['*.jar'])
26 |
27 | implementation 'androidx.appcompat:appcompat:1.1.0'
28 | testImplementation 'junit:junit:4.12'
29 | androidTestImplementation 'androidx.test:runner:1.2.0'
30 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
31 | implementation project(':okhttpencapsulation')
32 | // implementation 'com.ansen.http:okhttpencapsulation:1.0.5'
33 | }
34 |
--------------------------------------------------------------------------------
/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/ansen/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/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ansen/okhttp/test/activity/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.ansen.okhttp.test.activity;
2 |
3 | import android.Manifest;
4 | import android.content.pm.PackageManager;
5 | import android.content.res.AssetManager;
6 | import android.os.Build;
7 | import android.os.Environment;
8 | import android.os.Bundle;
9 | import android.util.Log;
10 | import android.view.View;
11 |
12 | import androidx.appcompat.app.AppCompatActivity;
13 |
14 | import com.ansen.http.net.NameValuePair;
15 | import com.ansen.okhttp.test.R;
16 | import com.ansen.okhttp.test.entity.User;
17 | import com.ansen.http.net.HTTPCaller;
18 | import com.ansen.http.net.RequestDataCallback;
19 |
20 | import java.io.File;
21 | import java.io.FileOutputStream;
22 | import java.io.IOException;
23 | import java.io.InputStream;
24 | import java.io.OutputStream;
25 | import java.util.ArrayList;
26 | import java.util.List;
27 |
28 | import io.github.lizhangqu.coreprogress.ProgressUIListener;
29 |
30 | public class MainActivity extends AppCompatActivity implements View.OnClickListener {
31 | private String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
32 | private final int PERMS_REQUEST_CODE = 200;
33 |
34 | @Override
35 | protected void onCreate(Bundle savedInstanceState) {
36 | super.onCreate(savedInstanceState);
37 | setContentView(R.layout.activity_main);
38 |
39 | findViewById(R.id.tv_get).setOnClickListener(this);
40 | findViewById(R.id.tv_get_sync).setOnClickListener(this);
41 | findViewById(R.id.tv_post).setOnClickListener(this);
42 | findViewById(R.id.tv_post_sync).setOnClickListener(this);
43 | findViewById(R.id.tv_upload_file).setOnClickListener(this);
44 | findViewById(R.id.tv_upload_file_progress).setOnClickListener(this);
45 | findViewById(R.id.tv_upload_file_content).setOnClickListener(this);
46 | findViewById(R.id.tv_upload_file_content_progress).setOnClickListener(this);
47 | findViewById(R.id.tv_download_file).setOnClickListener(this);
48 | findViewById(R.id.tv_modify_version).setOnClickListener(this);
49 |
50 | if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {//Android 6.0以上版本需要获取权限
51 | requestPermissions(perms,PERMS_REQUEST_CODE);//请求权限
52 | }
53 | }
54 |
55 | @Override
56 | public void onClick(View v) {
57 | if (v.getId() == R.id.tv_get) {
58 | HTTPCaller.getInstance().get(User.class, "http://139.196.35.30:8080/OkHttpTest/getUserInfo.do?per=123", requestDataCallback);
59 | } else if(v.getId()==R.id.tv_get_sync){
60 | getSync();
61 | }else if (v.getId() == R.id.tv_post) {
62 | List postParam = new ArrayList<>();
63 | postParam.add(new NameValuePair("username","ansen"));
64 | postParam.add(new NameValuePair("password","123"));
65 | HTTPCaller.getInstance().post(User.class, "http://139.196.35.30:8080/OkHttpTest/login.do", postParam, requestDataCallback);
66 | } else if(v.getId()==R.id.tv_post_sync){
67 | postSync();
68 | }else if (v.getId() == R.id.tv_upload_file) {
69 | updaloadFile(null);
70 | }else if (v.getId() == R.id.tv_upload_file_progress) {
71 | updaloadFile(new ProgressUIListener(){
72 | @Override
73 | public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
74 | Log.i("ansen","numBytes:"+numBytes+" totalBytes:"+totalBytes+" percent:"+percent+" speed:"+speed);
75 | }
76 | });
77 | }else if(v.getId()==R.id.tv_upload_file_content){
78 | byte[] bytes=getUploadFileBytes();//获取文件内容存入byte数组
79 | HTTPCaller.getInstance().postFile(User.class, "http://139.196.35.30:8080/OkHttpTest/uploadFile.do", null, "upload_file","test.txt",bytes,requestDataCallback);
80 | }else if(v.getId()==R.id.tv_upload_file_content_progress){
81 | byte[] bytes=getUploadFileBytes();//获取文件内容存入byte数组
82 | HTTPCaller.getInstance().postFile(User.class, "http://139.196.35.30:8080/OkHttpTest/uploadFile.do", null, "upload_file", "test.txt", bytes, requestDataCallback, new ProgressUIListener() {
83 | @Override
84 | public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
85 | Log.i("ansen","upload file content numBytes:"+numBytes+" totalBytes:"+totalBytes+" percent:"+percent+" speed:"+speed);
86 | }
87 | });
88 | }else if(v.getId()==R.id.tv_download_file){//下载文件
89 | String saveFilePath=Environment.getExternalStorageDirectory() + "/test/test222.txt";
90 | HTTPCaller.getInstance().downloadFile("http://139.196.35.30:8080/OkHttpTest/upload/test.txt",saveFilePath,null,new ProgressUIListener(){
91 | @Override
92 | public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
93 | Log.i("ansen","dowload file content numBytes:"+numBytes+" totalBytes:"+totalBytes+" percent:"+percent+" speed:"+speed);
94 | }
95 | });
96 | }else if(v.getId()==R.id.tv_modify_version){
97 | HTTPCaller.getInstance().updateCommonField("version_code","2");//更新公共字段版本号的值
98 | }
99 | }
100 |
101 | private void updaloadFile(ProgressUIListener progressUIListener){
102 | List postParam = new ArrayList<>();
103 | postParam.add(new NameValuePair("username", "ansen"));
104 | postParam.add(new NameValuePair("password", "123"));
105 | String filePath=copyFile();//复制一份文件到sdcard上,并且获取文件路径
106 | postParam.add(new NameValuePair("upload_file",filePath,true));
107 | if(progressUIListener==null){//上传文件没有回调进度条
108 | HTTPCaller.getInstance().postFile(User.class, "http://139.196.35.30:8080/OkHttpTest/uploadFile.do", null, postParam, requestDataCallback);
109 | }else{//上传文件并且回调上传进度
110 | HTTPCaller.getInstance().postFile(User.class, "http://139.196.35.30:8080/OkHttpTest/uploadFile.do", null, postParam, requestDataCallback,progressUIListener);
111 | }
112 | }
113 |
114 | @Override
115 | public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
116 | switch (permsRequestCode) {
117 | case PERMS_REQUEST_CODE:
118 | boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
119 | if (storageAccepted) {
120 |
121 | } else {
122 | Log.i("MainActivity", "没有写磁盘的判断退出APP");
123 | finish();
124 | }
125 | break;
126 |
127 | }
128 | }
129 |
130 | private RequestDataCallback requestDataCallback = new RequestDataCallback() {
131 | @Override
132 | public void dataCallback(User user) {
133 | if(user==null){
134 | Log.i("ansen", "请求失败");
135 | }else{
136 | Log.i("ansen", "获取用户信息:" + user.toString());
137 | }
138 | }
139 | };
140 |
141 | private byte[] getUploadFileBytes(){
142 | byte[] bytes=null;
143 | try {
144 | InputStream inputStream = getAssets().open("test.txt");
145 | Log.i("ansen","文件长度:"+inputStream.available());
146 | bytes = new byte[inputStream.available()];
147 | inputStream.read(bytes);
148 | inputStream.close();
149 | } catch (IOException e) {
150 | e.printStackTrace();
151 | }
152 | return bytes;
153 | }
154 |
155 | /**
156 | * 如果sd卡存在这个文件就先删除
157 | * 然后再从assets下把test.txt复制到sd卡上
158 | * @return
159 | */
160 | private String copyFile() {
161 | AssetManager assetManager = this.getAssets();
162 | String newFilePath=Environment.getExternalStorageDirectory() + "/test/test.txt";
163 |
164 | File file=new File(newFilePath);
165 | if(file.exists()){
166 | file.delete();
167 | }
168 |
169 | try {
170 | InputStream in = assetManager.open("test.txt");
171 | OutputStream out = new FileOutputStream(newFilePath);
172 | byte[] buffer = new byte[1024];
173 | int read;
174 | while ((read = in.read(buffer)) != -1) {
175 | out.write(buffer, 0, read);
176 | }
177 | in.close();
178 | out.flush();
179 | out.close();
180 | } catch (Exception e) {
181 | Log.e("tag", e.getMessage());
182 | }
183 | return newFilePath;
184 | }
185 |
186 |
187 | //在Android中UI线程是不能访问网络的,如果是同步请求网络,需要放在子线程中
188 | private void getSync(){
189 | new Thread(){
190 | @Override
191 | public void run() {
192 | User user=HTTPCaller.getInstance().getSync(User.class,"http://139.196.35.30:8080/OkHttpTest/getUserInfo.do?per=123");
193 | Log.i("ansen","get sync 用户name:"+user.getUsername());
194 | }
195 | }.start();
196 | }
197 |
198 | private void postSync(){
199 | new Thread(){
200 | @Override
201 | public void run() {
202 | List postParam = new ArrayList<>();
203 | postParam.add(new NameValuePair("username","ansen"));
204 | postParam.add(new NameValuePair("password","123"));
205 | User user=HTTPCaller.getInstance().postSync(User.class,"http://139.196.35.30:8080/OkHttpTest/login.do",postParam);
206 | Log.i("ansen","post sync 用户name:"+user.getUsername());
207 | }
208 | }.start();
209 | }
210 | }
211 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ansen/okhttp/test/app/MyApplication.java:
--------------------------------------------------------------------------------
1 | package com.ansen.okhttp.test.app;
2 |
3 | import android.app.Application;
4 |
5 | import com.ansen.http.entity.HttpConfig;
6 | import com.ansen.http.net.HTTPCaller;
7 |
8 | /**
9 | * Created by ansen
10 | * Create Time 2017-06-10
11 | */
12 | public class MyApplication extends Application{
13 | @Override
14 | public void onCreate() {
15 | super.onCreate();
16 |
17 | HttpConfig httpConfig=new HttpConfig();
18 | httpConfig.setAgent(true);//有代理的情况能不能访问
19 | httpConfig.setDebug(true);//是否debug模式 如果是debug模式打印log
20 | httpConfig.setTagName("ansen");//打印log的tagname
21 |
22 | //可以添加一些公共字段 每个接口都会带上
23 | httpConfig.addCommonField("pf","android");
24 | httpConfig.addCommonField("version_code","1");
25 |
26 | //初始化HTTPCaller类
27 | HTTPCaller.getInstance().setHttpConfig(httpConfig);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ansen/okhttp/test/entity/BaseProtocol.java:
--------------------------------------------------------------------------------
1 | package com.ansen.okhttp.test.entity;
2 |
3 | /**
4 | * Created by ansen
5 | * Create Time 2017-06-10
6 | */
7 | public class BaseProtocol {
8 | private String errorReason;
9 |
10 | public String getErrorReason() {
11 | return errorReason;
12 | }
13 |
14 | public void setErrorReason(String errorReason) {
15 | this.errorReason = errorReason;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/app/src/main/java/com/ansen/okhttp/test/entity/User.java:
--------------------------------------------------------------------------------
1 | package com.ansen.okhttp.test.entity;
2 |
3 | /**
4 | * Created by ansen
5 | * Create Time 2017-06-10
6 | */
7 | public class User extends BaseProtocol{
8 | private String password;
9 | private String username;
10 |
11 | public String getPassword() {
12 | return password;
13 | }
14 |
15 | public void setPassword(String password) {
16 | this.password = password;
17 | }
18 |
19 | public String getUsername() {
20 | return username;
21 | }
22 |
23 | public void setUsername(String username) {
24 | this.username = username;
25 | }
26 |
27 | @Override
28 | public String toString() {
29 | return "User{" +
30 | "password='" + password + '\'' +
31 | ", username='" + username + '\'' +
32 | '}';
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
17 |
18 |
23 |
24 |
29 |
30 |
35 |
36 |
41 |
42 |
47 |
48 |
53 |
54 |
59 |
60 |
65 |
66 |
71 |
72 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ansen666/OkHttpEncapsulation/d475510220f89419aa25e055d920625413a61193/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ansen666/OkHttpEncapsulation/d475510220f89419aa25e055d920625413a61193/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ansen666/OkHttpEncapsulation/d475510220f89419aa25e055d920625413a61193/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ansen666/OkHttpEncapsulation/d475510220f89419aa25e055d920625413a61193/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ansen666/OkHttpEncapsulation/d475510220f89419aa25e055d920625413a61193/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 | OkHttpEncapsulation
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/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 | // maven {url "http://maven.aliyun.com/nexus/content/groups/public/" }
6 | google()
7 | jcenter()
8 | maven { url 'https://jitpack.io' }
9 | }
10 |
11 | dependencies {
12 | classpath 'com.android.tools.build:gradle:3.5.0'
13 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
14 | }
15 | }
16 |
17 | allprojects {
18 | repositories {
19 | // maven {url "http://maven.aliyun.com/nexus/content/groups/public/" }
20 | google()
21 | jcenter()
22 | maven { url 'https://jitpack.io' }
23 | }
24 | }
25 |
26 | task clean(type: Delete) {
27 | delete rootProject.buildDir
28 | }
29 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ansen666/OkHttpEncapsulation/d475510220f89419aa25e055d920625413a61193/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Oct 10 20:32:57 CST 2019
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-5.4.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 |
--------------------------------------------------------------------------------
/okhttpencapsulation/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/okhttpencapsulation/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.github.dcendents.android-maven'
3 | group='com.ansen.http'//com.github.{你的的账号名}
4 |
5 | android {
6 | compileSdkVersion 29
7 | buildToolsVersion "29.0.0"
8 |
9 | defaultConfig {
10 | minSdkVersion 15
11 | targetSdkVersion 29
12 | versionCode 1
13 | versionName "1.0"
14 |
15 | }
16 | }
17 |
18 | dependencies {
19 | implementation fileTree(dir: 'libs', include: ['*.jar'])
20 | implementation 'androidx.appcompat:appcompat:1.1.0'
21 |
22 | api 'com.squareup.okhttp3:okhttp:4.9.3' //okhttp
23 | api 'com.google.code.gson:gson:2.8.6' //解析jsons数据
24 | api 'io.github.lizhangqu:coreprogress:1.0.2' //上传下载回调监听
25 | }
26 |
--------------------------------------------------------------------------------
/okhttpencapsulation/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/ansen/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 |
--------------------------------------------------------------------------------
/okhttpencapsulation/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/okhttpencapsulation/src/main/java/com/ansen/http/entity/HttpConfig.java:
--------------------------------------------------------------------------------
1 | package com.ansen.http.entity;
2 |
3 | import com.ansen.http.net.NameValuePair;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | /**
9 | * Created by ansen
10 | * Create Time 2017-06-10
11 | */
12 | public class HttpConfig {
13 | private boolean debug=false;//true:debug模式
14 | private String userAgent="";//用户代理 它是一个特殊字符串头,使得服务器能够识别客户使用的操作系统及版本、CPU 类型、浏览器及版本、浏览器渲染引擎、浏览器语言、浏览器插件等。
15 | private boolean agent=true;//有代理的情况能不能访问,true:有代理能访问 false:有代理不能访问
16 | private String tagName="Http";
17 |
18 | private int connectTimeout=10;//连接超时时间 单位:秒
19 | private int writeTimeout=10;//写入超时时间 单位:秒
20 | private int readTimeout=30;//读取超时时间 单位:秒
21 |
22 | //通用字段
23 | private List commonField=new ArrayList<>();
24 |
25 | public boolean isDebug() {
26 | return debug;
27 | }
28 |
29 | public void setDebug(boolean debug) {
30 | this.debug = debug;
31 | }
32 |
33 | public String getUserAgent() {
34 | return userAgent;
35 | }
36 |
37 | public void setUserAgent(String userAgent) {
38 | this.userAgent = userAgent;
39 | }
40 |
41 | public boolean isAgent() {
42 | return agent;
43 | }
44 |
45 | public void setAgent(boolean agent) {
46 | this.agent = agent;
47 | }
48 |
49 | public String getTagName() {
50 | return tagName;
51 | }
52 |
53 | public void setTagName(String tagName) {
54 | this.tagName = tagName;
55 | }
56 |
57 | public List getCommonField() {
58 | return commonField;
59 | }
60 |
61 | public int getConnectTimeout() {
62 | return connectTimeout;
63 | }
64 |
65 | public void setConnectTimeout(int connectTimeout) {
66 | this.connectTimeout = connectTimeout;
67 | }
68 |
69 | public int getWriteTimeout() {
70 | return writeTimeout;
71 | }
72 |
73 | public void setWriteTimeout(int writeTimeout) {
74 | this.writeTimeout = writeTimeout;
75 | }
76 |
77 | public int getReadTimeout() {
78 | return readTimeout;
79 | }
80 |
81 | public void setReadTimeout(int readTimeout) {
82 | this.readTimeout = readTimeout;
83 | }
84 |
85 | /**
86 | * 更新参数
87 | * @param key
88 | * @param value
89 | */
90 | public void updateCommonField(String key,String value){
91 | boolean result = true;
92 | for(int i=0;i=0;i--){
111 | if(commonField.get(i).equals(key)){
112 | commonField.remove(i);
113 | }
114 | }
115 | }
116 |
117 | /**
118 | * 添加请求参数
119 | * @param key
120 | * @param value
121 | */
122 | public void addCommonField(String key,String value){
123 | commonField.add(new NameValuePair(key,value));
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/okhttpencapsulation/src/main/java/com/ansen/http/net/HTTPCaller.java:
--------------------------------------------------------------------------------
1 | package com.ansen.http.net;
2 |
3 | import android.os.Handler;
4 | import android.os.Message;
5 | import android.text.TextUtils;
6 | import android.util.Log;
7 |
8 | import com.ansen.http.entity.HttpConfig;
9 | import com.ansen.http.util.Util;
10 | import com.google.gson.Gson;
11 |
12 | import java.io.File;
13 | import java.io.IOException;
14 | import java.io.UnsupportedEncodingException;
15 | import java.util.ArrayList;
16 | import java.util.Collections;
17 | import java.util.List;
18 | import java.util.Map;
19 | import java.util.WeakHashMap;
20 | import java.util.concurrent.TimeUnit;
21 |
22 | import io.github.lizhangqu.coreprogress.ProgressHelper;
23 | import io.github.lizhangqu.coreprogress.ProgressUIListener;
24 | import okhttp3.CacheControl;
25 | import okhttp3.Call;
26 | import okhttp3.Callback;
27 | import okhttp3.FormBody;
28 | import okhttp3.MediaType;
29 | import okhttp3.MultipartBody;
30 | import okhttp3.OkHttpClient;
31 | import okhttp3.Request;
32 | import okhttp3.RequestBody;
33 | import okhttp3.Response;
34 | import okhttp3.ResponseBody;
35 | import okio.BufferedSink;
36 | import okio.BufferedSource;
37 | import okio.Okio;
38 |
39 | /**
40 | * HTTP请求发起和数据解析转换
41 | * Created by ansen
42 | * Create Time 2014年9月18日 下午9:24:50
43 | * update time 2017-06-10
44 | */
45 | public class HTTPCaller {
46 | private static HTTPCaller _instance = null;
47 | private OkHttpClient client;//okhttp对象
48 | private Map requestHandleMap = null;//以URL为KEY存储的请求
49 | private CacheControl cacheControl = null;//缓存控制器
50 |
51 | private Gson gson = null;
52 |
53 | private HttpConfig httpConfig=new HttpConfig();//配置信息
54 |
55 | private HTTPCaller() {}
56 |
57 | public static HTTPCaller getInstance(){
58 | if (_instance == null) {
59 | _instance = new HTTPCaller();
60 | }
61 | return _instance;
62 | }
63 |
64 | /**
65 | * 设置配置信息 这个方法必需要调用一次
66 | * @param httpConfig
67 | */
68 | public void setHttpConfig(HttpConfig httpConfig) {
69 | this.httpConfig = httpConfig;
70 |
71 | client = new OkHttpClient.Builder()
72 | .connectTimeout(httpConfig.getConnectTimeout(), TimeUnit.SECONDS)
73 | .writeTimeout(httpConfig.getWriteTimeout(), TimeUnit.SECONDS)
74 | .readTimeout(httpConfig.getReadTimeout(), TimeUnit.SECONDS)
75 | .build();
76 |
77 | gson = new Gson();
78 | requestHandleMap = Collections.synchronizedMap(new WeakHashMap());
79 | cacheControl =new CacheControl.Builder().noStore().noCache().build();//不使用缓存
80 | }
81 |
82 | public void get(Class clazz,final String url,final RequestDataCallback callback) {
83 | this.get(clazz,url,null,callback,true);
84 | }
85 |
86 | public void get(Class clazz,final String url,Header[] header,final RequestDataCallback callback) {
87 | this.get(clazz,url,header,callback,true);
88 | }
89 |
90 | /**
91 | * get请求
92 | * @param clazz json对应类的类型
93 | * @param url 请求url
94 | * @param header 请求头
95 | * @param callback 回调接口
96 | * @param autoCancel 是否自动取消 true:同一时间请求一个接口多次 只保留最后一个
97 | * @param
98 | */
99 | public void get(final Class clazz,final String url,Header[] header,final RequestDataCallback callback, boolean autoCancel){
100 | if (checkAgent()) {
101 | return;
102 | }
103 | add(url,getBuilder(url, header, new MyHttpResponseHandler(clazz,url,callback)),autoCancel);
104 | }
105 |
106 | private Call getBuilder(String url, Header[] header, HttpResponseHandler responseCallback) {
107 | url=Util.getMosaicParameter(url,httpConfig.getCommonField());//拼接公共参数
108 | // Log.i("ansen","访问的url"+url);
109 | Request.Builder builder = new Request.Builder();
110 | builder.url(url);
111 | builder.get();
112 | return execute(builder, header, responseCallback);
113 | }
114 |
115 | public T getSync(Class clazz, String url){
116 | return getSync(clazz,url,null);
117 | }
118 |
119 | public T getSync(Class clazz, String url, Header[] header) {
120 | if (checkAgent()) {
121 | return null;
122 | }
123 | url=Util.getMosaicParameter(url,httpConfig.getCommonField());//拼接公共参数
124 | Request.Builder builder = new Request.Builder();
125 | builder.url(url);
126 | builder.get();
127 | byte[] bytes = execute(builder,header);
128 | try {
129 | String str = new String(bytes, "utf-8");
130 | if (clazz != null) {
131 | T t = gson.fromJson(str, clazz);
132 | return t;
133 | }
134 | } catch (Exception e) {
135 | printLog("getSync HTTPCaller:" + e.toString());
136 | }
137 | return null;
138 | }
139 |
140 | public void post(final Class clazz,final String url, List params, RequestDataCallback callback) {
141 | this.post(clazz,url, null, params, callback,true);
142 | }
143 |
144 | public void post(final Class clazz,final String url, Header[] header, List params, RequestDataCallback callback) {
145 | this.post(clazz,url, header, params, callback,true);
146 | }
147 |
148 | /**
149 | *
150 | * @param clazz json对应类的类型
151 | * @param url 请求url
152 | * @param header 请求头
153 | * @param params 参数
154 | * @param callback 回调
155 | * @param autoCancel 是否自动取消 true:同一时间请求一个接口多次 只保留最后一个
156 | * @param
157 | */
158 | public void post(final Class clazz,final String url, Header[] header, final List params, final RequestDataCallback callback, boolean autoCancel) {
159 | if (checkAgent()) {
160 | return;
161 | }
162 | add(url,postBuilder(url, header, params, new MyHttpResponseHandler(clazz,url,callback)),autoCancel);
163 | }
164 |
165 | public T postSync(Class clazz, String url, List form) {
166 | return postSync(clazz,url,form,null);
167 | }
168 |
169 | public T postSync(Class clazz, String url, List form,Header[] header) {
170 | if (checkAgent()) {
171 | return null;
172 | }
173 | // Log.i("ansen","url:"+url);
174 | Request.Builder builder=getRequestBuild(url,form);
175 | byte[] bytes = execute(builder,header);
176 | try {
177 | String result = new String(bytes, "utf-8");
178 | if (clazz != null && !TextUtils.isEmpty(result)) {
179 | T t = gson.fromJson(result,clazz);
180 | return t;
181 | }
182 | } catch (UnsupportedEncodingException e) {
183 | e.printStackTrace();
184 | }
185 | return null;
186 | }
187 |
188 | public byte[] postSync(String url,List form){
189 | return postSync(url,form);
190 | }
191 |
192 | public byte[] postSync(String url,List form,Header[] header) {
193 | if (checkAgent()) {
194 | return null;
195 | }
196 | Request.Builder builder=getRequestBuild(url,form);
197 | return execute(builder, header);
198 | }
199 |
200 | private Call postBuilder(String url, Header[] header, List form, HttpResponseHandler responseCallback) {
201 | try {
202 | Request.Builder builder=getRequestBuild(url,form);
203 | return execute(builder, header, responseCallback);
204 | } catch (Exception e) {
205 | if (responseCallback != null)
206 | responseCallback.onFailure(-1, e.getMessage().getBytes());
207 | }
208 | return null;
209 | }
210 |
211 | private Request.Builder getRequestBuild(String url,List form){
212 | if(form==null){
213 | form=new ArrayList<>();
214 | }
215 | form.addAll(httpConfig.getCommonField());//添加公共字段
216 | FormBody.Builder formBuilder = new FormBody.Builder();
217 | for (NameValuePair item : form) {
218 | if(TextUtils.isEmpty(item.getValue())){
219 | printLog("字段:"+item.getName()+"的值为null");
220 | continue;
221 | }
222 | formBuilder.add(item.getName(),item.getValue());
223 | }
224 | RequestBody requestBody = formBuilder.build();
225 | Request.Builder builder = new Request.Builder();
226 | builder.url(url);
227 | builder.post(requestBody);
228 | return builder;
229 | }
230 |
231 | /**
232 | * 上传文件
233 | * @param clazz json对应类的类型
234 | * @param url 请求url
235 | * @param header 请求头
236 | * @param form 请求参数
237 | * @param callback 回调
238 | * @param
239 | */
240 | public void postFile(final Class clazz, final String url, Header[] header,List form,final RequestDataCallback callback) {
241 | postFile(url, header, form, new MyHttpResponseHandler(clazz,url,callback),null);
242 | }
243 |
244 | /**
245 | * 上传文件
246 | * @param clazz json对应类的类型
247 | * @param url 请求url
248 | * @param header 请求头
249 | * @param form 请求参数
250 | * @param callback 回调
251 | * @param progressUIListener 上传文件进度
252 | * @param
253 | */
254 | public void postFile(final Class clazz, final String url, Header[] header,List form,final RequestDataCallback callback,ProgressUIListener progressUIListener) {
255 | add(url, postFile(url, header, form, new MyHttpResponseHandler(clazz,url,callback),progressUIListener));
256 | }
257 |
258 | /**
259 | * 上传文件
260 | * @param clazz json对应类的类型
261 | * @param url 请求url
262 | * @param header 请求头
263 | * @param name 名字
264 | * @param fileName 文件名
265 | * @param fileContent 文件内容
266 | * @param callback 回调
267 | * @param
268 | */
269 | public void postFile(final Class clazz,final String url,Header[] header,String name,String fileName,byte[] fileContent,final RequestDataCallback callback){
270 | postFile(clazz,url,header,name,fileName,fileContent,callback,null);
271 | }
272 |
273 | /**
274 | * 上传文件
275 | * @param clazz json对应类的类型
276 | * @param url 请求url
277 | * @param header 请求头
278 | * @param name 名字
279 | * @param fileName 文件名
280 | * @param fileContent 文件内容
281 | * @param callback 回调
282 | * @param progressUIListener 回调上传进度
283 | * @param
284 | */
285 | public void postFile(Class clazz,final String url,Header[] header,String name,String fileName,byte[] fileContent,final RequestDataCallback callback,ProgressUIListener progressUIListener) {
286 | add(url,postFile(url, header,name,fileName,fileContent,new MyHttpResponseHandler(clazz,url,callback),progressUIListener));
287 | }
288 |
289 | public void downloadFile(String url,String saveFilePath, Header[] header,ProgressUIListener progressUIListener) {
290 | downloadFile(url,saveFilePath, header, progressUIListener,true);
291 | }
292 |
293 | public void downloadFile(String url,String saveFilePath, Header[] header,ProgressUIListener progressUIListener,boolean autoCancel) {
294 | if (checkAgent()) {
295 | return;
296 | }
297 | add(url,downloadFileSendRequest(url,saveFilePath, header, progressUIListener),autoCancel);
298 | }
299 |
300 | private Call downloadFileSendRequest(String url,final String saveFilePath,Header[] header,final ProgressUIListener progressUIListener){
301 | Request.Builder builder = new Request.Builder();
302 | builder.url(url);
303 | builder.get();
304 | return execute(builder, header, new DownloadFileResponseHandler(url,saveFilePath,progressUIListener));
305 | }
306 |
307 | private Call postFile(String url, Header[] header,List form,HttpResponseHandler responseCallback,ProgressUIListener progressUIListener){
308 | try {
309 | MultipartBody.Builder builder = new MultipartBody.Builder();
310 | builder.setType(MultipartBody.FORM);
311 | MediaType mediaType = MediaType.parse("application/octet-stream");
312 |
313 | form.addAll(httpConfig.getCommonField());//添加公共字段
314 |
315 | for(int i=form.size()-1;i>=0;i--){
316 | NameValuePair item = form.get(i);
317 | if(item.isFile()){//上传文件
318 | File myFile = new File(item.getValue());
319 | if (myFile.exists()){
320 | String fileName = Util.getFileName(item.getValue());
321 | builder.addFormDataPart(item.getName(), fileName,RequestBody.create(mediaType, myFile));
322 | }
323 | }else{
324 | builder.addFormDataPart(item.getName(), item.getValue());
325 | }
326 | }
327 |
328 | RequestBody requestBody;
329 | if(progressUIListener==null){//不需要回调进度
330 | requestBody=builder.build();
331 | }else{//需要回调进度
332 | requestBody = ProgressHelper.withProgress(builder.build(),progressUIListener);
333 | }
334 | Request.Builder requestBuider = new Request.Builder();
335 | requestBuider.url(url);
336 | requestBuider.post(requestBody);
337 | return execute(requestBuider, header, responseCallback);
338 | } catch (Exception e) {
339 | e.printStackTrace();
340 | Log.e(httpConfig.getTagName(),e.toString());
341 | if (responseCallback != null)
342 | responseCallback.onFailure(-1, e.getMessage().getBytes());
343 | }
344 | return null;
345 | }
346 |
347 | private Call postFile(String url, Header[] header,String name,String filename,byte[] fileContent, HttpResponseHandler responseCallback,ProgressUIListener progressUIListener) {
348 | try {
349 | MultipartBody.Builder builder = new MultipartBody.Builder();
350 | builder.setType(MultipartBody.FORM);
351 | MediaType mediaType = MediaType.parse("application/octet-stream");
352 | builder.addFormDataPart(name,filename,RequestBody.create(mediaType, fileContent));
353 |
354 | List form = new ArrayList<>(2);
355 | form.addAll(httpConfig.getCommonField());//添加公共字段
356 | for (NameValuePair item : form) {
357 | builder.addFormDataPart(item.getName(),item.getValue());
358 | }
359 |
360 | RequestBody requestBody;
361 | if(progressUIListener==null){//不需要回调进度
362 | requestBody=builder.build();
363 | }else{//需要回调进度
364 | requestBody = ProgressHelper.withProgress(builder.build(),progressUIListener);
365 | }
366 | Request.Builder requestBuider = new Request.Builder();
367 | requestBuider.url(url);
368 | requestBuider.post(requestBody);
369 | return execute(requestBuider, header,responseCallback);
370 | } catch (Exception e) {
371 | if (httpConfig.isDebug()) {
372 | e.printStackTrace();
373 | Log.e(httpConfig.getTagName(), e.toString());
374 | }
375 | if (responseCallback != null)
376 | responseCallback.onFailure(-1, e.getMessage().getBytes());
377 | }
378 | return null;
379 | }
380 |
381 | //异步执行
382 | private Call execute(Request.Builder builder, Header[] header, Callback responseCallback) {
383 | Call call = getCall(builder, header);
384 | if (call != null) {
385 | call.enqueue(responseCallback);
386 | }
387 | return call;
388 | }
389 |
390 | //同步执行
391 | private byte[] execute(Request.Builder builder, Header[] header) {
392 | Call call = getCall(builder, header);
393 | byte[] body = "".getBytes();
394 | try {
395 | Response response = call.execute();
396 | body = response.body().bytes();
397 | } catch (Exception e) {
398 | e.printStackTrace();
399 | }
400 | return body;
401 | }
402 |
403 | private Call getCall(Request.Builder builder, Header[] header) {
404 | boolean hasUa = false;
405 | if (header == null) {
406 | builder.header("Connection","close");
407 | builder.header("Accept", "*/*");
408 | } else {
409 | for (Header h : header) {
410 | builder.header(h.getName(), h.getValue());
411 | if (!hasUa && h.getName().equals("User-Agent")) {
412 | hasUa = true;
413 | }
414 | }
415 | }
416 | if (!hasUa&&!TextUtils.isEmpty(httpConfig.getUserAgent())){
417 | builder.header("User-Agent",httpConfig.getUserAgent());
418 | }
419 | Request request = builder.cacheControl(cacheControl).build();
420 | return client.newCall(request);
421 | }
422 |
423 | public class DownloadFileResponseHandler implements Callback{
424 | private String saveFilePath;
425 | private ProgressUIListener progressUIListener;
426 | private String url;
427 |
428 | public DownloadFileResponseHandler(String url,String saveFilePath,ProgressUIListener progressUIListener){
429 | this.url=url;
430 | this.saveFilePath=saveFilePath;
431 | this.progressUIListener=progressUIListener;
432 | }
433 |
434 | @Override
435 | public void onFailure(Call call, IOException e) {
436 | clear(url);
437 | try {
438 | printLog(url + " " + -1 + " " + new String(e.getMessage().getBytes(), "utf-8"));
439 | } catch (UnsupportedEncodingException encodingException) {
440 | encodingException.printStackTrace();
441 | }
442 | }
443 |
444 | @Override
445 | public void onResponse(Call call, Response response) throws IOException {
446 | printLog(url + " code:" + response.code());
447 | clear(url);
448 |
449 | ResponseBody responseBody = ProgressHelper.withProgress(response.body(),progressUIListener);
450 | BufferedSource source = responseBody.source();
451 |
452 | File outFile = new File(saveFilePath);
453 | outFile.delete();
454 | outFile.createNewFile();
455 |
456 | BufferedSink sink = Okio.buffer(Okio.sink(outFile));
457 | source.readAll(sink);
458 | sink.flush();
459 | source.close();
460 | }
461 | }
462 |
463 | public class MyHttpResponseHandler extends HttpResponseHandler {
464 | private Class clazz;
465 | private String url;
466 | private RequestDataCallback callback;
467 |
468 | public MyHttpResponseHandler(Class clazz,String url,RequestDataCallback callback){
469 | this.clazz=clazz;
470 | this.url=url;
471 | this.callback=callback;
472 | }
473 |
474 | @Override
475 | public void onFailure(int status, byte[] data) {
476 | clear(url);
477 | try {
478 | printLog(url + " " + status + " " + new String(data, "utf-8"));
479 | } catch (UnsupportedEncodingException e) {
480 | e.printStackTrace();
481 | }
482 | sendCallback(callback);
483 | }
484 |
485 | @Override
486 | public void onSuccess(int status,final Header[] headers, byte[] responseBody) {
487 | try {
488 | clear(url);
489 | String str = new String(responseBody,"utf-8");
490 | printLog(url + " " + status + " " + str);
491 | T t = gson.fromJson(str, clazz);
492 | sendCallback(status,t,responseBody,callback);
493 | } catch (Exception e){
494 | if (httpConfig.isDebug()) {
495 | e.printStackTrace();
496 | printLog("自动解析错误:" + e.toString());
497 | }
498 | sendCallback(callback);
499 | }
500 | }
501 | }
502 |
503 | private void autoCancel(String function){
504 | Call call = requestHandleMap.remove(function);
505 | if (call != null) {
506 | call.cancel();
507 | }
508 | }
509 |
510 | private void add(String url,Call call) {
511 | add(url,call,true);
512 | }
513 |
514 | /**
515 | * 保存请求信息
516 | * @param url 请求url
517 | * @param call http请求call
518 | * @param autoCancel 自动取消
519 | */
520 | private void add(String url,Call call,boolean autoCancel) {
521 | if (!TextUtils.isEmpty(url)){
522 | if (url.contains("?")) {//get请求需要去掉后面的参数
523 | url=url.substring(0,url.indexOf("?"));
524 | }
525 | if(autoCancel){
526 | autoCancel(url);//如果同一时间对api进行多次请求,自动取消之前的
527 | }
528 | requestHandleMap.put(url,call);
529 | }
530 | }
531 |
532 | private void clear(String url){
533 | if (url.contains("?")) {//get请求需要去掉后面的参数
534 | url=url.substring(0,url.indexOf("?"));
535 | }
536 | requestHandleMap.remove(url);
537 | }
538 |
539 | private void printLog(String content){
540 | if(httpConfig.isDebug()){
541 | Log.i(httpConfig.getTagName(),content);
542 | }
543 | }
544 |
545 | /**
546 | * 检查代理
547 | * @return
548 | */
549 | private boolean checkAgent() {
550 | if (httpConfig.isAgent()){
551 | return false;
552 | } else {
553 | String proHost = android.net.Proxy.getDefaultHost();
554 | int proPort = android.net.Proxy.getDefaultPort();
555 | if (proHost==null || proPort<0){
556 | return false;
557 | }else {
558 | Log.i(httpConfig.getTagName(),"有代理,不能访问");
559 | return true;
560 | }
561 | }
562 | }
563 |
564 | //更新字段值
565 | public void updateCommonField(String key,String value){
566 | httpConfig.updateCommonField(key,value);
567 | }
568 |
569 | public void removeCommonField(String key){
570 | httpConfig.removeCommonField(key);
571 | }
572 |
573 | public void addCommonField(String key,String value){
574 | httpConfig.addCommonField(key,value);
575 | }
576 |
577 | private void sendCallback(RequestDataCallback callback){
578 | sendCallback(-1,null,null,callback);
579 | }
580 |
581 | private void sendCallback(int status,T data,byte[] body,RequestDataCallback callback){
582 | CallbackMessage msgData = new CallbackMessage();
583 | msgData.body = body;
584 | msgData.status = status;
585 | msgData.data = data;
586 | msgData.callback = callback;
587 |
588 | Message msg = handler.obtainMessage();
589 | msg.obj = msgData;
590 | handler.sendMessage(msg);
591 | }
592 |
593 | private Handler handler=new Handler(){
594 | @Override
595 | public void handleMessage(Message msg) {
596 | CallbackMessage data = (CallbackMessage)msg.obj;
597 | data.callback();
598 | }
599 | };
600 |
601 | private class CallbackMessage{
602 | public RequestDataCallback callback;
603 | public T data;
604 | public byte[] body;
605 | public int status;
606 |
607 | public void callback(){
608 | if(callback!=null){
609 | if(data==null){
610 | callback.dataCallback(null);
611 | }else{
612 | callback.dataCallback(status,data,body);
613 | }
614 | }
615 | }
616 | }
617 | }
618 |
--------------------------------------------------------------------------------
/okhttpencapsulation/src/main/java/com/ansen/http/net/Header.java:
--------------------------------------------------------------------------------
1 | package com.ansen.http.net;
2 |
3 | /**
4 | * Created by apple on 16/11/30.
5 | */
6 | public class Header extends NameValuePair {
7 | public Header(String name, String value){
8 | super(name,value);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/okhttpencapsulation/src/main/java/com/ansen/http/net/HttpResponseHandler.java:
--------------------------------------------------------------------------------
1 | package com.ansen.http.net;
2 |
3 | import java.io.IOException;
4 |
5 | import okhttp3.Call;
6 | import okhttp3.Callback;
7 | import okhttp3.Headers;
8 | import okhttp3.Response;
9 |
10 | /**
11 | * @ClassName: HttpResponseHandler
12 | * @Description: TODO(HTTP回调类)
13 | * @author guopeng
14 | * @date 2014 2014年9月21日 下午5:42:04
15 | */
16 | public abstract class HttpResponseHandler implements Callback {
17 | public HttpResponseHandler() {
18 | }
19 |
20 | /**
21 | *
22 | * @param call
23 | * @param e
24 | */
25 | public void onFailure(Call call, IOException e){
26 | onFailure(-1,e.getMessage().getBytes());
27 | }
28 |
29 | /**
30 | *
31 | * @param call
32 | * @param response
33 | * @throws IOException
34 | */
35 | public void onResponse(Call call, Response response) throws IOException {
36 | int code =response.code();
37 | byte[] body = response.body().bytes();
38 | if(code>299){
39 | onFailure(response.code(),body);
40 | }else{
41 | Headers headers = response.headers();
42 | Header[] hs = new Header[headers.size()];
43 |
44 | for (int i=0;i {
10 | //返回json对象
11 | public void dataCallback(T obj) {
12 | }
13 |
14 | //返回http状态和json对象
15 | public void dataCallback(int status, T obj) {
16 | dataCallback(obj);
17 | }
18 |
19 | //返回http状态、json对象和http原始数据
20 | public void dataCallback(int status, T obj, byte[] body) {
21 | dataCallback(status, obj);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/okhttpencapsulation/src/main/java/com/ansen/http/util/Util.java:
--------------------------------------------------------------------------------
1 | package com.ansen.http.util;
2 |
3 | import android.text.TextUtils;
4 |
5 | import com.ansen.http.net.NameValuePair;
6 |
7 | import java.net.URLEncoder;
8 | import java.util.List;
9 |
10 | /**
11 | * Created by ansen
12 | * Create Time 2017-06-09
13 | */
14 | public class Util {
15 | /**
16 | * 获取文件名称
17 | * @param filename
18 | * @return
19 | */
20 | public static String getFileName(String filename){
21 | int start=filename.lastIndexOf("/");
22 | // int end=filename.lastIndexOf(".");
23 | if(start!=-1){
24 | return filename.substring(start+1,filename.length());
25 | }else{
26 | return null;
27 | }
28 | }
29 |
30 | /**
31 | * 拼接公共参数
32 | * @param url
33 | * @param commonField
34 | * @return
35 | */
36 | public static String getMosaicParameter(String url, List commonField){
37 | if (TextUtils.isEmpty(url))
38 | return "";
39 | if (url.contains("?")) {
40 | url = url + "&";
41 | } else {
42 | url = url + "?";
43 | }
44 | url += getCommonFieldString(commonField);
45 | return url;
46 | }
47 |
48 | /**
49 | *
50 | * @param commonField
51 | * @return
52 | */
53 | private static String getCommonFieldString(List commonField){
54 | StringBuffer sb = new StringBuffer();
55 | try{
56 | int i=0;
57 | for (NameValuePair item:commonField) {
58 | if(i>0){
59 | sb.append("&");
60 | }
61 | sb.append(item.getName());
62 | sb.append('=');
63 | sb.append(URLEncoder.encode(item.getValue(),"utf-8"));
64 | i++;
65 | }
66 | }catch (Exception e){
67 |
68 | }
69 | return sb.toString();
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/okhttpencapsulation/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | okhttpencapsulation
3 |
4 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':okhttpencapsulation'
2 |
--------------------------------------------------------------------------------