32 | * ClassName: AsyncHttpUtil 33 | * Description:http请求工具类 34 | * Create by: 罗旭东 35 | * Date: 2016年10月13日 下午2:57:44 36 | *37 | */ 38 | public class AsyncHttpUtil { 39 | /** 全局使用同一个AsyncHttpClient对象 */ 40 | private static AsyncHttpClient mHttpClient = new AsyncHttpClient(); 41 | 42 | public static long sStartTime = System.nanoTime(); 43 | 44 | /** 45 | * 普通get请求 46 | * @return 47 | */ 48 | public static GetBuilder get() { 49 | return new GetBuilder(); 50 | } 51 | 52 | /** 53 | * 普通post请求 54 | * @return 55 | */ 56 | public static PostBuilder post() { 57 | return new PostBuilder(); 58 | } 59 | 60 | /** 61 | * form表单形式的提交请求 62 | * @return 63 | */ 64 | public static PostFormBuilder postForm() { 65 | return new PostFormBuilder(); 66 | } 67 | 68 | /** 69 | * 已json对象的方式的请求 70 | * @return 71 | */ 72 | public static PostJsonBuilder postJson() { 73 | return new PostJsonBuilder(); 74 | } 75 | 76 | /** 77 | * 数据内容为byte数组的请求 78 | * @return 79 | */ 80 | public static PostBytesBuilder postBytes() { 81 | return new PostBytesBuilder(); 82 | } 83 | 84 | /** 85 | * 文件上传 86 | * @return 87 | */ 88 | public static UploadFileBuilder uploadFile() { 89 | return new UploadFileBuilder(); 90 | } 91 | 92 | /** 93 | * 文件下载 94 | * @return 95 | */ 96 | public static DownloadFileBuilder downloadFile() { 97 | return new DownloadFileBuilder(); 98 | } 99 | 100 | /** 101 | * 显示日志 102 | */ 103 | public static void enableLog() { 104 | AsyncHttpLog.enableLog(); 105 | } 106 | 107 | /** 108 | * 创建一个新的http客户端 109 | * @return 110 | */ 111 | public static AsyncHttpClient newAsyncHttpClient() { 112 | return new AsyncHttpClient(); 113 | } 114 | 115 | /** 116 | * 增加证书 117 | * @param cerDatas 证书字符串 118 | */ 119 | public static void setSslSocketFactory(String[] cerDatas) { 120 | setSslSocketFactory(getHttpClient(), cerDatas); 121 | } 122 | 123 | public static void setSslSocketFactory(AsyncHttpClient asyncHttpClients, String[] cerDatas) { 124 | if (asyncHttpClients == null) { 125 | return; 126 | } 127 | asyncHttpClients.setSslSocketFactory(cerDatas); 128 | } 129 | 130 | /** 131 | * 增加证书 132 | * @param cerStreams 证书数据流 133 | */ 134 | public static void setSslSocketFactory(InputStream[] cerStreams) { 135 | setSslSocketFactory(getHttpClient(), cerStreams); 136 | } 137 | 138 | public static void setSslSocketFactory(AsyncHttpClient asyncHttpClients,InputStream[] cerStreams) { 139 | if (asyncHttpClients == null) { 140 | return; 141 | } 142 | 143 | asyncHttpClients.setSslSocketFactory(cerStreams); 144 | } 145 | 146 | /** 147 | * 信任所有证书,不安全 148 | */ 149 | public static void setNoSafeSslSocketFactory() { 150 | setSslSocketFactory((String[])null); 151 | } 152 | 153 | public static void setNoSafeSslSocketFactory(AsyncHttpClient asyncHttpClients) { 154 | if (asyncHttpClients == null) { 155 | return; 156 | } 157 | 158 | setSslSocketFactory(asyncHttpClients, (String[])null); 159 | } 160 | 161 | /** 162 | * 设置UA 163 | * @param userAgent 164 | */ 165 | public static void setUserAgent(String userAgent) { 166 | setUserAgent(getHttpClient(), userAgent); 167 | } 168 | 169 | public static void setUserAgent(AsyncHttpClient asyncHttpClients,String userAgent) { 170 | if (asyncHttpClients == null) { 171 | return; 172 | } 173 | 174 | asyncHttpClients.userAgent(userAgent).build(); 175 | } 176 | 177 | /** 178 | * 隐藏日志 179 | */ 180 | public static void disableLog() { 181 | AsyncHttpLog.disableLog(); 182 | } 183 | 184 | /** 185 | * 根据tag中断请求 186 | * @param tag 187 | */ 188 | public static void cancelTag(String tag) { 189 | AsyncHttpClient asyncHttpClient = getHttpClient(); 190 | for (Call call : asyncHttpClient.getOkHttpClient().dispatcher().queuedCalls()) { 191 | if (tag.equals(call.request().tag())) { 192 | call.cancel(); 193 | } 194 | } 195 | 196 | for (Call call : asyncHttpClient.getOkHttpClient().dispatcher().runningCalls()) { 197 | if (tag.equals(call.request().tag())) { 198 | call.cancel(); 199 | } 200 | } 201 | } 202 | 203 | /** 204 | * 中断所有请求 205 | */ 206 | public static void cancelAll() { 207 | AsyncHttpClient asyncHttpClient = getHttpClient(); 208 | for (Call call : asyncHttpClient.getOkHttpClient().dispatcher().queuedCalls()) { 209 | call.cancel(); 210 | } 211 | 212 | for (Call call : asyncHttpClient.getOkHttpClient().dispatcher().runningCalls()) { 213 | call.cancel(); 214 | } 215 | } 216 | 217 | private AsyncHttpUtil(AsyncHttpClient httpClient) { 218 | if (httpClient == null) { 219 | mHttpClient = new AsyncHttpClient(); 220 | } else { 221 | mHttpClient = httpClient; 222 | } 223 | } 224 | 225 | /** 226 | * 获取HttpClient 227 | * @return 228 | */ 229 | public static AsyncHttpClient getHttpClient() { 230 | if (mHttpClient == null) { 231 | synchronized (AsyncHttpUtil.class) { 232 | if (mHttpClient == null) { 233 | mHttpClient = new AsyncHttpClient(); 234 | } 235 | } 236 | } 237 | 238 | return mHttpClient; 239 | } 240 | } 241 | -------------------------------------------------------------------------------- /src/main/src/main/java/com/luoxudong/app/asynchttp/ContentType.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Title: ContentType.java 3 | * Description: 4 | * Copyright: Copyright (c) 2013-2015 luoxudong.com 5 | * Company: 个人 6 | * Author: 罗旭东 (hi@luoxudong.com) 7 | * Date: 2016年11月22日 下午3:48:48 8 | * Version: 1.0 9 | */ 10 | package com.luoxudong.app.asynchttp; 11 | 12 | /** 13 | *
14 | * ClassName: ContentType 15 | * Description:请求内容枚举类型 16 | * Create by: 罗旭东 17 | * Date: 2016年11月22日 下午3:48:48 18 | *19 | */ 20 | public enum ContentType { 21 | text("text/plain;charset=utf-8"), 22 | html("text/html;charset=utf-8"), 23 | octetStream("application/octet-stream"); 24 | 25 | private String value = null; 26 | 27 | ContentType(String value) { 28 | this.value = value; 29 | } 30 | 31 | public String getValue() { 32 | return value; 33 | } 34 | 35 | public void setValue(String value) { 36 | this.value = value; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/src/main/java/com/luoxudong/app/asynchttp/builder/DownloadFileBuilder.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Title: DownloadFileBuilder.java 3 | * Description: 下载文件的构建类 4 | * Copyright: Copyright (c) 2013-2015 luoxudong.com 5 | * Company: 个人 6 | * Author: 罗旭东 (hi@luoxudong.com) 7 | * Date: 2016年12月29日 上午10:58:18 8 | * Version: 1.0 9 | */ 10 | package com.luoxudong.app.asynchttp.builder; 11 | 12 | import com.luoxudong.app.asynchttp.AsyncHttpTask; 13 | import com.luoxudong.app.asynchttp.request.DownloadFileRequest; 14 | import com.luoxudong.app.asynchttp.request.PostBytesRequest; 15 | 16 | /** 17 | *
18 | * ClassName: DownloadFileBuilder 19 | * Description:下载文件的构建类,支持文件断点下载 20 | * Create by: 罗旭东 21 | * Date: 2016年12月29日 上午10:58:18 22 | *23 | */ 24 | public class DownloadFileBuilder extends RequestBuilder
18 | * ClassName: GetBuilder 19 | * Description:get请求Builder,支持返回内容为json对象 20 | * Create by: 罗旭东 21 | * Date: 2016年10月13日 下午2:54:16 22 | *23 | */ 24 | public class GetBuilder extends RequestBuilder
18 | * ClassName: PostBuilder 19 | * Description:普通Post请求构建类,支持返回参数为json对象 20 | * Create by: 罗旭东 21 | * Date: 2016年10月13日 下午6:04:02 22 | *23 | */ 24 | public class PostBuilder extends RequestBuilder
18 | * ClassName: PostBytesBuilder 19 | * Description:传输字节数组的构建类,请求内容和返回内容都为字节数组 20 | * Create by: 罗旭东 21 | * Date: 2016年12月29日 下午2:27:57 22 | *23 | */ 24 | public class PostBytesBuilder extends RequestBuilder
21 | * ClassName: PostFormBuilder 22 | * Description:Post提交form表单的构建类,支持返回参数为json对象 23 | * Create by: 罗旭东 24 | * Date: 2016年11月23日 上午11:02:59 25 | *26 | */ 27 | public class PostFormBuilder extends RequestBuilder
19 | * ClassName: PostJsonBuilder 20 | * Description:请求内容和返回内容都为json对象的构建类 21 | * Create by: 罗旭东 22 | * Date: 2016年12月29日 下午4:17:36 23 | *24 | */ 25 | public class PostJsonBuilder extends RequestBuilder
25 | * ClassName: RequestBuilder 26 | * Description:通用请求参数构造类 27 | * Create by: 罗旭东 28 | * Date: 2016年10月13日 下午2:53:32 29 | *30 | */ 31 | public abstract class RequestBuilder
22 | * ClassName: UploadFileBuilder 23 | * Description:上传文件构建类,支持多文件断点上传下载 24 | * Create by: 罗旭东 25 | * Date: 2016年11月23日 下午5:13:21 26 | *27 | */ 28 | public class UploadFileBuilder extends RequestBuilder
15 | * ClassName: JsonRequestCallable 16 | * Description:http普通json请求回调,回调方法在UI线程中运行 17 | * Create by: 罗旭东 18 | * Date: 2015年7月13日 下午3:30:59 19 | *20 | */ 21 | public abstract class JsonRequestCallable
17 | * ClassName: RequestCallable 18 | * Description:基础回调类,回调方法在UI线程中运行 19 | * Create by: 罗旭东 20 | * Date: 2015年7月13日 下午3:21:52 21 | *22 | */ 23 | public abstract class RequestCallable { 24 | /** 请求ID */ 25 | protected long mId = 0; 26 | 27 | /** 28 | * 开始请求 29 | */ 30 | public void onStart(){}; 31 | 32 | /** 33 | * 请求结束 34 | */ 35 | public void onFinish(){}; 36 | 37 | /** 38 | * 取消请求 39 | */ 40 | public void onCancel(){}; 41 | 42 | /** 43 | * 返回成功 44 | * @param headers 返回的http头部信息 45 | */ 46 | public void onSuccess(Map
14 | * ClassName: StringRequestCallable 15 | * Description:请求结果为普通字符串的回调类 16 | * Create by: 罗旭东 17 | * Date: 2016年12月30日 下午2:50:36 18 | *19 | */ 20 | public abstract class StringRequestCallable extends RequestCallable { 21 | /** 22 | * 请求成功 23 | * @param responseBody 普通字符串内容 24 | */ 25 | public abstract void onSuccess(String responseBody); 26 | } 27 | -------------------------------------------------------------------------------- /src/main/src/main/java/com/luoxudong/app/asynchttp/callable/UploadRequestCallable.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Title: UploadRequestCallable.java 3 | * Description: 4 | * Copyright: Copyright (c) 2013 luoxudong.com 5 | * Company: 个人 6 | * Author: 罗旭东 7 | * Date: 2015年7月17日 下午6:24:58 8 | * Version: 1.0 9 | */ 10 | package com.luoxudong.app.asynchttp.callable; 11 | 12 | /** 13 | * ClassName: UploadRequestCallable 14 | * Description:TODO(这里用一句话描述这个类的作用) 15 | * Create by: 16 | * Date: 2015年7月17日 下午6:24:58 17 | */ 18 | public abstract class UploadRequestCallable extends StringRequestCallable { 19 | /** 20 | * 开始上传 21 | */ 22 | public void onStartTransfer(){}; 23 | 24 | /** 25 | * 上传中 26 | * @param fileName 当前传输的文件名 27 | * @param totalLength 当前上传文件总大小 28 | * @param transferedLength 当前文件已上传大小 29 | */ 30 | public void onTransfering(String fileName, long totalLength, long transferedLength){}; 31 | 32 | /** 33 | * 上传成功 34 | * @param fileName 35 | */ 36 | public void onTransferSuc(String fileName){}; 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/src/main/java/com/luoxudong/app/asynchttp/cookie/ClearableCookieJar.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Francisco José Montiel Navarro. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.luoxudong.app.asynchttp.cookie; 18 | 19 | import okhttp3.CookieJar; 20 | 21 | /** 22 | * This interface extends {@link CookieJar} and adds methods to clear the cookies. 23 | */ 24 | public interface ClearableCookieJar extends CookieJar { 25 | 26 | /** 27 | * Clear all the session cookies while maintaining the persisted ones. 28 | */ 29 | void clearSession(); 30 | 31 | /** 32 | * Clear all the cookies from persistence and from the cache. 33 | */ 34 | void clear(); 35 | } 36 | -------------------------------------------------------------------------------- /src/main/src/main/java/com/luoxudong/app/asynchttp/cookie/PersistentCookieJar.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Francisco José Montiel Navarro. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.luoxudong.app.asynchttp.cookie; 18 | 19 | import com.luoxudong.app.asynchttp.cookie.cache.CookieCache; 20 | import com.luoxudong.app.asynchttp.cookie.persistence.CookiePersistor; 21 | import com.luoxudong.app.asynchttp.utils.AsyncHttpLog; 22 | 23 | import java.util.ArrayList; 24 | import java.util.Iterator; 25 | import java.util.List; 26 | 27 | import okhttp3.Cookie; 28 | import okhttp3.HttpUrl; 29 | 30 | public class PersistentCookieJar implements ClearableCookieJar { 31 | 32 | private CookieCache cache; 33 | private CookiePersistor persistor; 34 | 35 | public PersistentCookieJar(CookieCache cache, CookiePersistor persistor) { 36 | this.cache = cache; 37 | this.persistor = persistor; 38 | 39 | if (persistor != null) { 40 | this.cache.addAll(persistor.loadAll()); 41 | } 42 | } 43 | 44 | @Override 45 | synchronized public void saveFromResponse(HttpUrl url, List
28 | *
29 | * This new behaviour will be useful in determining when an already existing cookie in session must be overwritten.
30 | */
31 | class IdentifiableCookie {
32 |
33 | private Cookie cookie;
34 |
35 | static List
3 | * Title: DownloadFileResponseHandler.java
4 | * Description: 下载请求结果回调
5 | * Copyright: Copyright (c) 2014-2016 gjfax.com
6 | * Company: 广金所
7 | * Author: 罗旭东 (hi@luoxudong.com)
8 | * Date: 2017/1/24 11:58
9 | * Version: 1.0
10 | *
11 | */
12 | package com.luoxudong.app.asynchttp.handler;
13 |
14 | import android.os.Message;
15 |
16 | import com.luoxudong.app.asynchttp.AsyncHttpConst;
17 | import com.luoxudong.app.asynchttp.callable.DownloadRequestCallable;
18 | import com.luoxudong.app.asynchttp.callable.RequestCallable;
19 | import com.luoxudong.app.asynchttp.exception.AsyncHttpException;
20 | import com.luoxudong.app.asynchttp.exception.AsyncHttpExceptionCode;
21 | import com.luoxudong.app.asynchttp.utils.AsyncHttpLog;
22 |
23 | import java.io.File;
24 | import java.io.FileNotFoundException;
25 | import java.io.FileOutputStream;
26 | import java.io.IOException;
27 | import java.io.InputStream;
28 | import java.io.RandomAccessFile;
29 |
30 | import okhttp3.Response;
31 |
32 | /**
33 | *
34 | * Class: DownloadFileResponseHandler
35 | * Description: 下载请求结果回调
36 | * Author: 罗旭东 (hi@luoxudong.com)
37 | * Date: 2017/1/24 11:58
38 | * Version: 1.0
39 | *
40 | */
41 | public class DownloadFileResponseHandler extends ResponseHandler {
42 | private final String TAG = DownloadFileResponseHandler.class.getSimpleName();
43 |
44 | /** 开始传输 */
45 | protected static final int FILE_TRANSFER_START = 100;
46 | /** 传输中 */
47 | protected static final int FILE_TRANSFERING = 101;
48 | /** 传输缓存大小 */
49 | protected static final int BUFFER_SIZE = 200 * 1024;
50 | /** 断点下载起始位置 */
51 | private long mOffset = 0;
52 | /** 下载文件保存路径 */
53 | private String mFileDir = null;
54 | /** 下载文件名 */
55 | private String mFileName = null;
56 | /** 每次下载bffer大小 */
57 | private byte[] mBuffer = new byte[BUFFER_SIZE];
58 |
59 | public DownloadFileResponseHandler(String fileDir, String fileName, long offset, RequestCallable callable) {
60 | super(callable);
61 | mFileDir = fileDir;
62 | mFileName = fileName;
63 | mOffset = offset;
64 | }
65 |
66 | @Override
67 | protected void parseResponse(Response response) {
68 | boolean isChunked = "chunked".equalsIgnoreCase(response.header("Transfer-Encoding"));
69 |
70 | sendStartTransferMessage();//开始下载
71 |
72 | if (isChunked) {//chunked编码,不支持断点下载
73 | normalDownload(response);
74 | } else {//支持断点下载
75 | breakpointDownload(response);
76 | }
77 | }
78 |
79 | @Override
80 | protected void onSuccess(byte[] buffer) {
81 | onSuccess();
82 | }
83 |
84 | public void onSuccess() {
85 | if (mCallable != null && mCallable instanceof DownloadRequestCallable) {
86 | ((DownloadRequestCallable)mCallable).onSuccess();
87 | }
88 | }
89 |
90 | /**
91 | * 开始下载
92 | */
93 | protected void sendStartTransferMessage() {
94 | sendMessage(obtainMessage(FILE_TRANSFER_START, null));
95 | }
96 |
97 | /**
98 | * 正在传输
99 | */
100 | protected void sendTransferingMessage(long totalLength, long transferedLength) {
101 | sendMessage(obtainMessage(FILE_TRANSFERING, new long[]{totalLength, transferedLength}));
102 | }
103 |
104 | @Override
105 | protected void handlerMessageCustom(Message msg) {
106 | switch (msg.what) {
107 | case FILE_TRANSFER_START:
108 | if (mCallable != null && mCallable instanceof DownloadRequestCallable) {
109 | ((DownloadRequestCallable)mCallable).onStartTransfer();
110 | }
111 |
112 | break;
113 | case FILE_TRANSFERING:
114 | if (mCallable != null && mCallable instanceof DownloadRequestCallable) {
115 | long[] param = (long[])msg.obj;
116 | ((DownloadRequestCallable)mCallable).onTransfering(param[0], param[1]);
117 | }
118 | break;
119 | default:
120 | break;
121 | }
122 | }
123 |
124 | /**
125 | * 普通下载
126 | * @param response
127 | */
128 | private void normalDownload(Response response) {
129 | File localFile = new File(mFileDir, mFileName);
130 | int length = 0;
131 | long offset = 0;
132 |
133 | if (!localFile.getParentFile().exists()) {//文件夹不存在则创建文件夹
134 | localFile.getParentFile().mkdirs();
135 | } else {//不支持断点下载,删除原来的文件
136 | localFile.delete();
137 | }
138 |
139 | InputStream is = response.body().byteStream();
140 | FileOutputStream out = null;
141 |
142 | try {
143 | out = new FileOutputStream(localFile);
144 |
145 | long timeStamp = System.currentTimeMillis();
146 | while ((length = is.read(mBuffer)) != -1) {
147 | out.write(mBuffer, 0, length);
148 | offset += length;
149 |
150 | if ((System.currentTimeMillis() - timeStamp) >= AsyncHttpConst.TRANSFER_REFRESH_TIME_INTERVAL) {
151 | AsyncHttpLog.d(TAG, "下载进度:" + offset);
152 | sendTransferingMessage(offset + 1, offset);
153 | timeStamp = System.currentTimeMillis();// 每一秒调用一次
154 | }
155 | }
156 |
157 | sendTransferingMessage(offset, offset);
158 | sendSuccessMessage(response.headers(), null);
159 |
160 | } catch (IOException e) {
161 | sendFailureMessage(AsyncHttpExceptionCode.defaultExceptionCode.getErrorCode(), e);
162 | } finally {
163 | if (out != null) {
164 | try {
165 | out.close();
166 | } catch (IOException e) {
167 | sendFailureMessage(AsyncHttpExceptionCode.defaultExceptionCode.getErrorCode(), e);
168 | }
169 | }
170 | }
171 | }
172 |
173 | /**
174 | * 断点下载
175 | * @param response
176 | */
177 | private void breakpointDownload(Response response) {
178 | RandomAccessFile randomAccessFile = null;
179 | long totalLength = response.body().contentLength();//下载文件总长度
180 | InputStream is = response.body().byteStream();
181 |
182 | File localFile = new File(mFileDir, mFileName);
183 |
184 | if (!localFile.getParentFile().exists()) {//文件夹不存在则创建文件夹
185 | localFile.getParentFile().mkdirs();
186 | }
187 |
188 | if (localFile.exists() && localFile.length() != totalLength){//文件存在但大小不一致,则删除
189 | localFile.delete();
190 | }
191 |
192 | try {
193 | boolean isNewFile = !localFile.exists();
194 | randomAccessFile = new RandomAccessFile(localFile, "rw");
195 | if (isNewFile) {//如果是新文件则指定文件大小
196 | randomAccessFile.setLength(totalLength);
197 | }
198 |
199 | downloading(response, randomAccessFile);
200 | } catch (FileNotFoundException e1) {
201 | sendFailureMessage(AsyncHttpExceptionCode.defaultExceptionCode.getErrorCode(), new AsyncHttpException("文件不存在!"));
202 | return;
203 | } catch (IOException e) {
204 | if (randomAccessFile != null) {
205 | try {
206 | randomAccessFile.close();
207 | } catch (IOException e1) {
208 | e1.printStackTrace();
209 | }
210 | }
211 | sendFailureMessage(AsyncHttpExceptionCode.defaultExceptionCode.getErrorCode(), new AsyncHttpException("IO异常!"));
212 | return;
213 | }finally{
214 | if (randomAccessFile != null) {
215 | try {
216 | randomAccessFile.close();
217 | } catch (IOException e) {
218 |
219 | }
220 | }
221 | }
222 | }
223 |
224 | /**
225 | * 开始下载
226 | * @param response
227 | * @param randomAccessFile
228 | * @throws IOException
229 | */
230 | private void downloading(Response response, RandomAccessFile randomAccessFile) throws IOException {
231 | long offset = 0;
232 | int length = 0;
233 | InputStream is = response.body().byteStream();
234 | long totalLength = response.body().contentLength();//下载文件总长度
235 |
236 | //支持断点下载
237 | if (response.code() == 206) {
238 | offset = mOffset;
239 | }
240 |
241 | randomAccessFile.seek(offset);
242 |
243 | long timeStamp = System.currentTimeMillis();
244 | while (offset < totalLength && (length = is.read(mBuffer)) != -1) {
245 | offset += length;
246 | randomAccessFile.write(mBuffer, 0, length);
247 |
248 | if ((System.currentTimeMillis() - timeStamp) >= AsyncHttpConst.TRANSFER_REFRESH_TIME_INTERVAL || offset == totalLength) {
249 | AsyncHttpLog.d(TAG, "下载进度:" + offset + "/" + totalLength);
250 | sendTransferingMessage(totalLength, offset);
251 | timeStamp = System.currentTimeMillis();// 每一秒调用一次
252 | }
253 | }
254 |
255 | if (offset == totalLength) {//下载完成
256 | sendTransferingMessage(totalLength, totalLength);
257 | sendSuccessMessage(response.headers(), null);
258 | } else if (offset > totalLength) {
259 | sendFailureMessage(AsyncHttpExceptionCode.defaultExceptionCode.getErrorCode(), new AsyncHttpException("本地文件长度超过总长度!"));
260 | }
261 | }
262 |
263 | }
264 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/handler/JsonResponseHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Title: JsonResponseHandler.java
3 | * Description:
4 | * Copyright: Copyright (c) 2013-2015 luoxudong.com
5 | * Company: 个人
6 | * Author: 罗旭东 (hi@luoxudong.com)
7 | * Date: 2016年12月30日 下午3:28:02
8 | * Version: 1.0
9 | */
10 | package com.luoxudong.app.asynchttp.handler;
11 |
12 | import java.io.UnsupportedEncodingException;
13 |
14 | import android.text.TextUtils;
15 |
16 | import com.luoxudong.app.asynchttp.AsyncHttpConst;
17 | import com.luoxudong.app.asynchttp.callable.JsonRequestCallable;
18 | import com.luoxudong.app.asynchttp.callable.RequestCallable;
19 | import com.luoxudong.app.asynchttp.callable.StringRequestCallable;
20 | import com.luoxudong.app.asynchttp.interceptor.JsonResponseInterceptor;
21 | import com.luoxudong.app.asynchttp.utils.AsyncHttpLog;
22 |
23 | /**
24 | *
25 | * ClassName: JsonResponseHandler
26 | * Description:json结果请求回调
27 | * Create by: 罗旭东
28 | * Date: 2016年12月30日 下午3:28:02
29 | *
30 | */
31 | public class JsonResponseHandler extends StringResponseHandler {
32 | private final String TAG = JsonResponseHandler.class.getSimpleName();
33 | /** 返回json对应的映射类 */
34 | private Class mResponseClazz = null;
35 | /** 返回结果拦截器,可以自定义json解析器 */
36 | private JsonResponseInterceptor mResponseInterceptor = null;
37 |
38 | public JsonResponseHandler(Class responseClazz, JsonResponseInterceptor responseInterceptor, RequestCallable callable) {
39 | super(callable);
40 | mResponseClazz = responseClazz;
41 | mResponseInterceptor = responseInterceptor;
42 | }
43 |
44 | protected void onSuccess(String responseBody) {
45 | if (mCallable != null && mCallable instanceof JsonRequestCallable) {
46 | Object rspObject = null;
47 |
48 | AsyncHttpLog.i(TAG, responseBody);
49 |
50 | if (!TextUtils.isEmpty(responseBody) && mResponseInterceptor != null) {
51 | rspObject = mResponseInterceptor.convertJsonToObj(responseBody, mResponseClazz);
52 |
53 | if (!mResponseInterceptor.checkResponse(rspObject)) {//结果校验为通过
54 | ((JsonRequestCallable)mCallable).onFailed(mResponseInterceptor.getErrorCode(), mResponseInterceptor.getErrorMsg());
55 | return;
56 | }
57 | }
58 |
59 | ((JsonRequestCallable)mCallable).onSuccess(rspObject);
60 | } else {
61 | super.onSuccess(responseBody);
62 | }
63 | }
64 |
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/handler/ResponseHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Title: ResponseHandler.java
3 | * Description:
4 | * Copyright: Copyright (c) 2013-2015 luoxudong.com
5 | * Company: 个人
6 | * Author: 罗旭东 (hi@luoxudong.com)
7 | * Date: 2015年7月13日 下午5:22:32
8 | * Version: 1.0
9 | */
10 | package com.luoxudong.app.asynchttp.handler;
11 |
12 | import java.io.IOException;
13 |
14 | import okhttp3.Headers;
15 | import okhttp3.Response;
16 | import android.os.Handler;
17 | import android.os.Looper;
18 | import android.os.Message;
19 |
20 | import com.luoxudong.app.asynchttp.callable.RequestCallable;
21 | import com.luoxudong.app.asynchttp.exception.AsyncHttpException;
22 | import com.luoxudong.app.asynchttp.exception.AsyncHttpExceptionCode;
23 | import com.luoxudong.app.asynchttp.utils.AsyncHttpLog;
24 |
25 | /**
26 | * ClassName: ResponseHandler
27 | * Description:处理请求返回结果
28 | * Create by: 罗旭东
29 | * Date: 2015年7月13日 下午5:22:32
30 | */
31 | public class ResponseHandler {
32 | private static final String TAG = ResponseHandler.class.getSimpleName();
33 |
34 | /** 请求成功 */
35 | protected static final int SUCCESS_MESSAGE = 0;
36 | /** 请求失败 */
37 | protected static final int FAILURE_MESSAGE = 1;
38 | /** 开始请求 */
39 | protected static final int START_MESSAGE = 2;
40 | /** 请求完成 */
41 | protected static final int FINISH_MESSAGE = 3;
42 | /** 中断请求 */
43 | protected static final int CANCEL_MESSAGE = 4;
44 | /** 返回结果是否在主线程中执行 */
45 | private boolean mMainThread = false;
46 | /** 请求回调 */
47 | protected RequestCallable mCallable = null;
48 |
49 | private Handler mMainHandler = null;
50 |
51 | public ResponseHandler(RequestCallable callable) {
52 | mCallable = callable;
53 | // 检测当前线程是否有绑定looper,如果没有绑定则使用主线程的looper
54 |
55 | if (Looper.myLooper() != null) {
56 | mMainHandler = new Handler() {
57 | @Override
58 | public void handleMessage(Message msg) {
59 | ResponseHandler.this.handleMessage(msg);
60 | }
61 | };
62 | } else {
63 | mMainHandler = new Handler(Looper.getMainLooper()) {
64 | @Override
65 | public void handleMessage(Message msg) {
66 | ResponseHandler.this.handleMessage(msg);
67 | }
68 | };
69 | }
70 |
71 | }
72 |
73 | /**
74 | * 请求返回结果统一入口
75 | * @param response
76 | */
77 | public void onResponseSucess(Response response) {
78 | if (!response.isSuccessful()) {
79 | sendFailureMessage(AsyncHttpExceptionCode.httpResponseException.getErrorCode(), new AsyncHttpException(response.message()));
80 | return;
81 | }
82 |
83 | parseResponse(response);
84 |
85 | }
86 |
87 | /**
88 | * 解析返回数据
89 | * @param response
90 | */
91 | protected void parseResponse(Response response) {
92 | try {
93 | byte[] buffer = response.body().bytes();
94 | Headers headers = response.headers();
95 | response.close();
96 |
97 | sendSuccessMessage(headers, buffer);
98 | } catch (IOException e) {
99 | sendFailureMessage(AsyncHttpExceptionCode.httpResponseException.getErrorCode(), e);
100 | }
101 | }
102 |
103 | public void sendSuccessMessage(Headers headers, byte[] buffer) {
104 | sendMessage(obtainMessage(SUCCESS_MESSAGE, new Object[]{ headers, buffer}));
105 | }
106 |
107 | public void sendFailureMessage(int errorCode, Throwable e) {
108 | sendMessage(obtainMessage(FAILURE_MESSAGE, new Object[]{errorCode, e}));
109 | }
110 |
111 | public void sendStartMessage() {
112 | sendMessage(obtainMessage(START_MESSAGE, null));
113 | }
114 |
115 | public void sendFinishMessage() {
116 | sendMessage(obtainMessage(FINISH_MESSAGE, null));
117 | }
118 |
119 | public void sendCancelMessage(){
120 | sendMessage(obtainMessage(CANCEL_MESSAGE, null));
121 | }
122 |
123 | protected void handleMessage(Message msg) {
124 | Object[] response;
125 |
126 | switch(msg.what) {
127 | case SUCCESS_MESSAGE:
128 | response = (Object[])msg.obj;
129 | handleSuccessMessage((Headers) response[0], (byte[])response[1]);
130 | break;
131 | case FAILURE_MESSAGE:
132 | response = (Object[])msg.obj;
133 | handleFailureMessage((Integer)response[0], (Throwable)response[1]);
134 | break;
135 | case START_MESSAGE:
136 | onStart();
137 | break;
138 | case FINISH_MESSAGE:
139 | onFinish();
140 | break;
141 | case CANCEL_MESSAGE:
142 | onCancel();
143 | break;
144 | default:
145 | handlerMessageCustom(msg);
146 | break;
147 | }
148 | }
149 |
150 | protected void handleSuccessMessage(Headers headers, byte[] buffer) {
151 | if (mCallable != null) {
152 | mCallable.onSuccess(headers.toMultimap());
153 | }
154 |
155 | onSuccess(buffer);
156 | }
157 |
158 | protected void handlerMessageCustom(Message msg) {
159 |
160 | }
161 |
162 | protected void onStart() {
163 | if (mCallable != null){
164 | mCallable.onStart();
165 | }
166 | }
167 |
168 | protected void onFinish() {
169 | if (mCallable != null){
170 | mCallable.onFinish();
171 | }
172 | }
173 |
174 | protected void onCancel() {
175 | if (mCallable != null){
176 | mCallable.onCancel();
177 | }
178 | }
179 |
180 | protected void onSuccess(byte[] buffer) {
181 | if (mCallable != null) {
182 | mCallable.onSuccess(buffer);
183 | }
184 | }
185 |
186 | protected void handleFailureMessage(int errorCode, Throwable e) {
187 | onFailure(errorCode, e);
188 | }
189 |
190 | protected void onFailure(int errorCode, Throwable e) {
191 | String errorMsg = e.getMessage();
192 | AsyncHttpLog.e(TAG, "错误信息:" + errorMsg + "[" + errorCode + "]");
193 |
194 | if (mCallable != null) {
195 | mCallable.onFailed(errorCode, errorMsg);
196 | }
197 | }
198 |
199 | protected void sendMessage(Message msg) {
200 | if(mMainHandler != null && mMainThread){//需要在主线程中执行
201 | mMainHandler.sendMessage(msg);
202 | } else {
203 | handleMessage(msg);
204 | }
205 | }
206 |
207 | protected Message obtainMessage(int responseMessage, Object response) {
208 | Message msg = null;
209 | if(mMainHandler != null){
210 | msg = mMainHandler.obtainMessage(responseMessage, response);
211 | }else{
212 | msg = Message.obtain();
213 | msg.what = responseMessage;
214 | msg.obj = response;
215 | }
216 | return msg;
217 | }
218 |
219 | public void setMainThread(boolean mainThread) {
220 | mMainThread = mainThread;
221 | }
222 |
223 | }
224 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/handler/StringResponseHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Title: StringResponseHandler.java
3 | * Description:
4 | * Copyright: Copyright (c) 2013-2015 luoxudong.com
5 | * Company: 个人
6 | * Author: 罗旭东 (hi@luoxudong.com)
7 | * Date: 2016年11月22日 下午2:46:50
8 | * Version: 1.0
9 | */
10 | package com.luoxudong.app.asynchttp.handler;
11 |
12 | import java.io.UnsupportedEncodingException;
13 |
14 | import com.luoxudong.app.asynchttp.AsyncHttpConst;
15 | import com.luoxudong.app.asynchttp.callable.RequestCallable;
16 | import com.luoxudong.app.asynchttp.callable.StringRequestCallable;
17 | import com.luoxudong.app.asynchttp.utils.AsyncHttpLog;
18 |
19 | /**
20 | *
21 | * ClassName: StringResponseHandler
22 | * Description:返回结果为字符串类型的回调
23 | * Create by: 罗旭东
24 | * Date: 2016年11月22日 下午2:46:50
25 | *
26 | */
27 | public class StringResponseHandler extends ResponseHandler {
28 | private final String TAG = StringResponseHandler.class.getSimpleName();
29 |
30 | /**
31 | * @param callable
32 | */
33 | public StringResponseHandler(RequestCallable callable) {
34 | super(callable);
35 | }
36 |
37 | @Override
38 | protected void onSuccess(byte[] buffer) {
39 | super.onSuccess(buffer);
40 | try {
41 | onSuccess(buffer == null ? null : new String(buffer, AsyncHttpConst.HTTP_ENCODING));
42 | } catch (UnsupportedEncodingException e) {
43 | AsyncHttpLog.e(TAG, "不支持该编码");
44 | }
45 | }
46 |
47 | protected void onSuccess(String responseBody) {
48 | AsyncHttpLog.i(TAG, responseBody);
49 |
50 | if (mCallable != null && mCallable instanceof StringRequestCallable) {
51 | ((StringRequestCallable)mCallable).onSuccess(responseBody);
52 | } else {
53 | AsyncHttpLog.w(TAG, "回调类型错误!");
54 | }
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/handler/UploadFileResponseHandler.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * Title: UploadFileResponseHandler.java
4 | * Description:上传文件回调
5 | * Copyright: Copyright (c) 2014-2016 luoxudong.com
6 | * Company: 个人
7 | * Author: 罗旭东 (hi@luoxudong.com)
8 | * Date: 2017/1/13 17:27
9 | * Version: 1.0
10 | *
11 | */
12 | package com.luoxudong.app.asynchttp.handler;
13 |
14 | import android.os.Message;
15 |
16 | import com.luoxudong.app.asynchttp.AsyncHttpConst;
17 | import com.luoxudong.app.asynchttp.callable.RequestCallable;
18 | import com.luoxudong.app.asynchttp.callable.UploadRequestCallable;
19 | import com.luoxudong.app.asynchttp.exception.AsyncHttpExceptionCode;
20 | import com.luoxudong.app.asynchttp.utils.AsyncHttpLog;
21 |
22 | import java.io.UnsupportedEncodingException;
23 |
24 | /**
25 | *
26 | * Class: UploadFileResponseHandler
27 | * Description: 上传文件回调
28 | * Author: 罗旭东 (hi@luoxudong.com)
29 | * Date: 2017/1/24 12:02
30 | * Version: 1.0
31 | *
32 | */
33 | public class UploadFileResponseHandler extends ResponseHandler {
34 | private final String TAG = UploadFileResponseHandler.class.getSimpleName();
35 |
36 | /** 开始传输 */
37 | protected static final int FILE_TRANSFER_START = 100;
38 | /** 传输中 */
39 | protected static final int FILE_TRANSFERING = 101;
40 | /** 单个文件上传成功 */
41 | protected static final int FILE_TRANSFER_SEC = 102;
42 | /** 传输缓存大小 */
43 | protected static final int BUFFER_SIZE = 200 * 1024;
44 |
45 | public UploadFileResponseHandler(RequestCallable callable) {
46 | super(callable);
47 | }
48 |
49 | /**
50 | * 开始下载
51 | */
52 | public void sendStartTransferMessage() {
53 | sendMessage(obtainMessage(FILE_TRANSFER_START, null));
54 | }
55 |
56 | /**
57 | * 正在传输
58 | */
59 | public void sendTransferingMessage(String fileName, long totalLength, long transferedLength) {
60 | sendMessage(obtainMessage(FILE_TRANSFERING, new Object[]{fileName, totalLength, transferedLength}));
61 | }
62 |
63 | public void sendTransferSucMessage(String fileName) {
64 | sendMessage(obtainMessage(FILE_TRANSFER_SEC, fileName));
65 | }
66 |
67 | @Override
68 | protected void handlerMessageCustom(Message msg) {
69 | switch (msg.what) {
70 | case FILE_TRANSFER_START:
71 | if (mCallable != null && mCallable instanceof UploadRequestCallable) {
72 | ((UploadRequestCallable)mCallable).onStartTransfer();
73 | }
74 |
75 | break;
76 | case FILE_TRANSFERING:
77 | if (mCallable != null && mCallable instanceof UploadRequestCallable) {
78 | Object[] param = (Object[])msg.obj;
79 | ((UploadRequestCallable)mCallable).onTransfering((String)param[0], (long)param[1], (long)param[2]);
80 | }
81 | break;
82 | case FILE_TRANSFER_SEC:
83 | if (mCallable != null && mCallable instanceof UploadRequestCallable) {
84 | ((UploadRequestCallable)mCallable).onTransferSuc((String)msg.obj);
85 | }
86 | break;
87 | default:
88 | break;
89 | }
90 | }
91 |
92 | @Override
93 | protected void onSuccess(byte[] buffer) {
94 | try {
95 | onSuccess(buffer == null ? null : new String(buffer, AsyncHttpConst.HTTP_ENCODING));
96 | } catch (UnsupportedEncodingException e) {
97 | if (mCallable != null) {
98 | mCallable.onFailed(AsyncHttpExceptionCode.defaultExceptionCode.getErrorCode(), "不支持该编码!");
99 | }
100 | }
101 | }
102 |
103 | protected void onSuccess(String responseBody) {
104 | AsyncHttpLog.i(TAG, responseBody);
105 |
106 | if (mCallable != null && mCallable instanceof UploadRequestCallable) {
107 | ((UploadRequestCallable)mCallable).onSuccess(responseBody);
108 | } else {
109 | AsyncHttpLog.w(TAG, "回调类型错误!");
110 | }
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/https/MySslSocketFactory.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * Title: MySslSocketFactory.java
4 | * Description: 获取自定义sslSocket类
5 | * Copyright: Copyright (c) 2014-2016 gjfax.com
6 | * Company: 广金所
7 | * Author: 罗旭东 (hi@luoxudong.com)
8 | * Date: 2017/1/24 12:03
9 | * Version: 1.0
10 | *
11 | */
12 | package com.luoxudong.app.asynchttp.https;
13 |
14 | import java.io.IOException;
15 | import java.io.InputStream;
16 | import java.security.KeyManagementException;
17 | import java.security.KeyStore;
18 | import java.security.KeyStoreException;
19 | import java.security.NoSuchAlgorithmException;
20 | import java.security.UnrecoverableKeyException;
21 | import java.security.cert.CertificateException;
22 | import java.security.cert.CertificateFactory;
23 |
24 | import javax.net.ssl.KeyManager;
25 | import javax.net.ssl.KeyManagerFactory;
26 | import javax.net.ssl.SSLContext;
27 | import javax.net.ssl.TrustManager;
28 | import javax.net.ssl.TrustManagerFactory;
29 | import javax.net.ssl.X509TrustManager;
30 |
31 | /**
32 | *
33 | * Class: MySslSocketFactory
34 | * Description: 获取自定义sslsocket类
35 | * Author: 罗旭东 (hi@luoxudong.com)
36 | * Date: 2017/1/24 12:03
37 | * Version: 1.0
38 | *
39 | */
40 | public class MySslSocketFactory {
41 | public SSLParams getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password) {
42 | SSLParams sslParams = new SSLParams();
43 | try {
44 | TrustManager[] trustManagers = prepareTrustManager(certificates);
45 | KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
46 | SSLContext sslContext = SSLContext.getInstance("TLS");
47 | X509TrustManager trustManager = null;
48 | if (trustManagers != null) {
49 | trustManager = new MyTrustManager(trustManagers);
50 | } else {
51 | trustManager = new UnSafeTrustManager();
52 | }
53 | sslContext.init(keyManagers, new TrustManager[]{trustManager},null);
54 | sslParams.setSSLSocketFactory(sslContext.getSocketFactory());
55 | sslParams.setTrustManager(trustManager);
56 | return sslParams;
57 | } catch (NoSuchAlgorithmException e) {
58 | throw new AssertionError(e);
59 | } catch (KeyManagementException e) {
60 | throw new AssertionError(e);
61 | } catch (KeyStoreException e) {
62 | throw new AssertionError(e);
63 | }
64 | }
65 |
66 | private TrustManager[] prepareTrustManager(InputStream... certificates) {
67 | if (certificates == null || certificates.length <= 0) {
68 | return null;
69 | }
70 |
71 | try {
72 | CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
73 | KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
74 | keyStore.load(null);
75 | int index = 0;
76 | for (InputStream certificate : certificates) {
77 | String certificateAlias = Integer.toString(index++);
78 | keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
79 | try {
80 | if (certificate != null){
81 | certificate.close();
82 | }
83 | } catch (IOException e) {
84 | }
85 | }
86 | TrustManagerFactory trustManagerFactory = null;
87 |
88 | trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
89 | trustManagerFactory.init(keyStore);
90 |
91 | TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
92 |
93 | return trustManagers;
94 | } catch (NoSuchAlgorithmException e) {
95 | e.printStackTrace();
96 | } catch (CertificateException e) {
97 | e.printStackTrace();
98 | } catch (KeyStoreException e) {
99 | e.printStackTrace();
100 | } catch (Exception e) {
101 | e.printStackTrace();
102 | }
103 | return null;
104 |
105 | }
106 |
107 | private KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
108 | try {
109 | if (bksFile == null || password == null) {
110 | return null;
111 | }
112 |
113 | KeyStore clientKeyStore = KeyStore.getInstance("BKS");
114 | clientKeyStore.load(bksFile, password.toCharArray());
115 | KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
116 | keyManagerFactory.init(clientKeyStore, password.toCharArray());
117 | return keyManagerFactory.getKeyManagers();
118 |
119 | } catch (KeyStoreException e) {
120 | e.printStackTrace();
121 | } catch (NoSuchAlgorithmException e) {
122 | e.printStackTrace();
123 | } catch (UnrecoverableKeyException e) {
124 | e.printStackTrace();
125 | } catch (CertificateException e) {
126 | e.printStackTrace();
127 | } catch (IOException e) {
128 | e.printStackTrace();
129 | } catch (Exception e) {
130 | e.printStackTrace();
131 | }
132 | return null;
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/https/MyTrustManager.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * Title: MyTrustManager.java
4 | * Description: 信任证书管理类
5 | * Copyright: Copyright (c) 2014-2016 gjfax.com
6 | * Company: 广金所
7 | * Author: 罗旭东 (hi@luoxudong.com)
8 | * Date: 2017/1/24 12:03
9 | * Version: 1.0
10 | *
11 | */
12 | package com.luoxudong.app.asynchttp.https;
13 |
14 | import android.util.Log;
15 |
16 | import java.security.KeyStore;
17 | import java.security.KeyStoreException;
18 | import java.security.NoSuchAlgorithmException;
19 | import java.security.cert.CertificateException;
20 | import java.security.cert.X509Certificate;
21 |
22 | import javax.net.ssl.TrustManager;
23 | import javax.net.ssl.TrustManagerFactory;
24 | import javax.net.ssl.X509TrustManager;
25 |
26 | /**
27 | *
28 | * Class: MyTrustManager
29 | * Description: 信任证书管理类
30 | * Author: 罗旭东 (hi@luoxudong.com)
31 | * Date: 2017/1/24 12:03
32 | * Version: 1.0
33 | *
34 | */
35 | public class MyTrustManager implements X509TrustManager {
36 | private X509TrustManager mDefaultTrustManager = null;
37 | private X509TrustManager mLocalTrustManager = null;
38 |
39 | public MyTrustManager(TrustManager[] trustManagers) throws NoSuchAlgorithmException, KeyStoreException {
40 | TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
41 | trustManagerFactory.init((KeyStore) null);
42 | mDefaultTrustManager = chooseTrustManager(trustManagerFactory.getTrustManagers());
43 | mLocalTrustManager = chooseTrustManager(trustManagers);
44 | }
45 |
46 | @Override
47 | public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
48 |
49 | }
50 |
51 | @Override
52 | public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
53 | try {
54 | mDefaultTrustManager.checkServerTrusted(chain, authType);
55 | } catch (CertificateException e) {
56 | mLocalTrustManager.checkServerTrusted(chain, authType);
57 | }
58 | }
59 |
60 |
61 | @Override
62 | public X509Certificate[] getAcceptedIssuers()
63 | {
64 | return new X509Certificate[0];
65 | }
66 |
67 | private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {
68 | for (TrustManager trustManager : trustManagers) {
69 | if (trustManager instanceof X509TrustManager) {
70 | return (X509TrustManager) trustManager;
71 | }
72 | }
73 | return null;
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/https/SSLParams.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * Title: SSLParams.java
4 | * Description: 设置ssl链接参数类
5 | * Copyright: Copyright (c) 2014-2016 gjfax.com
6 | * Company: 广金所
7 | * Author: 罗旭东 (hi@luoxudong.com)
8 | * Date: 2017/1/24 12:04
9 | * Version: 1.0
10 | *
11 | */
12 | package com.luoxudong.app.asynchttp.https;
13 |
14 | import javax.net.ssl.SSLSocketFactory;
15 | import javax.net.ssl.X509TrustManager;
16 |
17 | /**
18 | *
19 | * Class: SSLParams
20 | * Description: 设置ssl链接参数类
21 | * Author: 罗旭东 (hi@luoxudong.com)
22 | * Date: 2017/1/24 12:04
23 | * Version: 1.0
24 | *
25 | */
26 | public class SSLParams {
27 | private SSLSocketFactory mSSLSocketFactory = null;
28 |
29 | private X509TrustManager mTrustManager = null;
30 |
31 | public SSLSocketFactory getSSLSocketFactory() {
32 | return mSSLSocketFactory;
33 | }
34 |
35 | public void setSSLSocketFactory(SSLSocketFactory sSLSocketFactory) {
36 | mSSLSocketFactory = sSLSocketFactory;
37 | }
38 |
39 | public X509TrustManager getTrustManager() {
40 | return mTrustManager;
41 | }
42 |
43 | public void setTrustManager(X509TrustManager trustManager) {
44 | mTrustManager = trustManager;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/https/UnSafeHostnameVerifier.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * Title: UnSafeHostnameVerifier.java
4 | * Description:
5 | * Copyright: Copyright (c) 2014-2016 gjfax.com
6 | * Company: 广金所
7 | * Author: 罗旭东 (hi@luoxudong.com)
8 | * Date: 2017/1/24 12:04
9 | * Version: 1.0
10 | *
11 | */
12 | package com.luoxudong.app.asynchttp.https;
13 |
14 | import javax.net.ssl.HostnameVerifier;
15 | import javax.net.ssl.SSLSession;
16 |
17 | /**
18 | *
19 | * Class: UnSafeHostnameVerifier
20 | * Description:
21 | * Author: 罗旭东 (hi@luoxudong.com)
22 | * Date: 2017/1/24 12:05
23 | * Version: 1.0
24 | *
25 | */
26 | public class UnSafeHostnameVerifier implements HostnameVerifier {
27 | @Override
28 | public boolean verify(String hostname, SSLSession session) {
29 | return true;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/https/UnSafeTrustManager.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * Title: UnSafeTrustManager.java
4 | * Description:
5 | * Copyright: Copyright (c) 2014-2016 gjfax.com
6 | * Company: 广金所
7 | * Author: 罗旭东 (hi@luoxudong.com)
8 | * Date: 2017/1/24 12:05
9 | * Version: 1.0
10 | *
11 | */
12 | package com.luoxudong.app.asynchttp.https;
13 |
14 | import java.security.cert.CertificateException;
15 | import java.security.cert.X509Certificate;
16 |
17 | import javax.net.ssl.X509TrustManager;
18 |
19 | /**
20 | *
21 | * Class: UnSafeTrustManager
22 | * Description:
23 | * Author: 罗旭东 (hi@luoxudong.com)
24 | * Date: 2017/1/24 12:05
25 | * Version: 1.0
26 | *
27 | */
28 | public class UnSafeTrustManager implements X509TrustManager {
29 | @Override
30 | public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
31 | }
32 |
33 | @Override
34 | public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
35 | }
36 |
37 | @Override
38 | public X509Certificate[] getAcceptedIssuers() {
39 | return new java.security.cert.X509Certificate[]{};
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/interceptor/JsonRequestInterceptor.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Title: JsonRequestInterceptor.java
3 | * Description:
4 | * Copyright: Copyright (c) 2013-2015 luoxudong.com
5 | * Company: 个人
6 | * Author: 罗旭东 (hi@luoxudong.com)
7 | * Date: 2016年1月7日 下午3:00:00
8 | * Version: 1.0
9 | */
10 | package com.luoxudong.app.asynchttp.interceptor;
11 |
12 |
13 | /**
14 | * ClassName: JsonRequestInterceptor
15 | * Description:发送Json请求时拦截器,在发送请求之前处理数据,需要把json对象转换成字符串
16 | * Create by: 罗旭东
17 | * Date: 2016年1月7日 下午3:00:00
18 | */
19 | public abstract class JsonRequestInterceptor {
20 | /**
21 | * 把指定对象转换成json字符串
22 | * @param requestObj
23 | * @return
24 | */
25 | public abstract String convertJsonToObj(Object requestObj);
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/interceptor/JsonResponseInterceptor.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Title: JsonResponseInterceptor.java
3 | * Description:
4 | * Copyright: Copyright (c) 2013-2015 luoxudong.com
5 | * Company: 个人
6 | * Author: 罗旭东 (hi@luoxudong.com)
7 | * Date: 2016年1月7日 下午3:01:00
8 | * Version: 1.0
9 | */
10 | package com.luoxudong.app.asynchttp.interceptor;
11 |
12 | import com.luoxudong.app.asynchttp.exception.AsyncHttpExceptionCode;
13 |
14 | /**
15 | * ClassName: JsonResponseInterceptor
16 | * Description:发送Json返回拦截器,需要将json字符串转换成对象
17 | * Create by: 罗旭东
18 | * Date: 2016年1月7日 下午3:01:00
19 | */
20 | public abstract class JsonResponseInterceptor
26 | * ClassName: UserAgentInterceptor
27 | * Description:userAgent拦截器
28 | * Create by: 罗旭东
29 | * Date: 2016年11月23日 上午11:55:05
30 | *
31 | */
32 | public class UserAgentInterceptor implements Interceptor {
33 | private String mUserAgent = null;
34 |
35 | public UserAgentInterceptor() {
36 | mUserAgent = AsyncHttpConst.sUserAgent;
37 | }
38 |
39 | public UserAgentInterceptor(String userAgent) {
40 | mUserAgent = userAgent;
41 | }
42 |
43 | @Override
44 | public Response intercept(Chain chain) throws IOException
45 | {
46 | Request request = chain.request();
47 | Request newRequest = request.newBuilder()
48 | .removeHeader(AsyncHttpConst.HEADER_USER_AGENT)
49 | .addHeader(AsyncHttpConst.HEADER_USER_AGENT, checkUserAgent(mUserAgent))
50 | .build();
51 | return chain.proceed(newRequest);
52 | }
53 |
54 | /**
55 | * 对不合法字符处理,见Headers->checkNameAndValue
56 | * @param userAgent
57 | * @return
58 | */
59 | private String checkUserAgent(String userAgent) {
60 | StringBuffer sb = new StringBuffer();
61 | for (int i = 0, length = userAgent.length(); i < length; i++) {
62 | char c = userAgent.charAt(i);
63 | if (c <= '\u001f' && c!='\u0009' || c >= '\u007f') {
64 | sb.append(String.format("\\u%04x", (int) c));
65 | } else {
66 | sb.append(c);
67 | }
68 | }
69 | return sb.toString();
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/model/FileWrapper.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Title: FileWrapper.java
3 | * Description:
4 | * Copyright: Copyright (c) 2013 luoxudong.com
5 | * Company: 个人
6 | * Author: 罗旭东
7 | * Date: 2015年7月17日 下午5:11:54
8 | * Version: 1.0
9 | */
10 | package com.luoxudong.app.asynchttp.model;
11 |
12 | import java.io.File;
13 |
14 | /**
15 | * ClassName: FileWrapper
16 | * Description:上传文件参数封装类
17 | * Create by:
18 | * Date: 2015年7月17日 下午5:11:54
19 | */
20 | public class FileWrapper {
21 | /** 上传的文件 */
22 | private File mFile = null;
23 | /** 上传的起始地址 */
24 | private long mStartPos = 0;
25 | /** 上传的块大小,默认上传全部文件 */
26 | private long mBlockSize = 0;
27 |
28 | public File getFile() {
29 | return mFile;
30 | }
31 |
32 | public void setFile(File file) {
33 | mFile = file;
34 | }
35 |
36 | public long getStartPos() {
37 | return mStartPos;
38 | }
39 |
40 | public void setStartPos(long startPos) {
41 | mStartPos = startPos;
42 | }
43 |
44 | public long getBlockSize() {
45 | return mBlockSize;
46 | }
47 |
48 | public void setBlockSize(long blockSize) {
49 | mBlockSize = blockSize;
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/request/AsyncHttpRequest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Title: AsyncHttpRequest.java
3 | * Description:
4 | * Copyright: Copyright (c) 2013-2015 luoxudong.com
5 | * Company: 个人
6 | * Author: 罗旭东 (hi@luoxudong.com)
7 | * Date: 2016年10月13日 下午3:43:41
8 | * Version: 1.0
9 | */
10 | package com.luoxudong.app.asynchttp.request;
11 |
12 | import android.net.Uri;
13 | import android.text.TextUtils;
14 |
15 | import com.luoxudong.app.asynchttp.AsyncHttpClient;
16 | import com.luoxudong.app.asynchttp.AsyncHttpConst;
17 | import com.luoxudong.app.asynchttp.AsyncHttpTask;
18 | import com.luoxudong.app.asynchttp.AsyncHttpUtil;
19 | import com.luoxudong.app.asynchttp.builder.RequestBuilder;
20 | import com.luoxudong.app.asynchttp.callable.RequestCallable;
21 | import com.luoxudong.app.asynchttp.exception.AsyncHttpException;
22 | import com.luoxudong.app.asynchttp.exception.AsyncHttpExceptionCode;
23 | import com.luoxudong.app.asynchttp.handler.ResponseHandler;
24 | import com.luoxudong.app.asynchttp.utils.AsyncHttpLog;
25 |
26 | import java.util.Iterator;
27 | import java.util.Map;
28 | import java.util.Set;
29 |
30 | import okhttp3.Headers;
31 | import okhttp3.Request;
32 |
33 | /**
34 | *
35 | * ClassName: AsyncHttpRequest
36 | * Description:各种请求基类
37 | * Create by: 罗旭东
38 | * Date: 2016年10月13日 下午3:43:41
39 | *
40 | */
41 | public abstract class AsyncHttpRequest {
42 | private long mId = 0;
43 | /** http请求实例 */
44 | private AsyncHttpClient mAsyncHttpClient = null;
45 | /** URL */
46 | protected String mUrl = null;
47 | /** 是否在主线程中执行 */
48 | protected boolean mMainThread = false;
49 | /** 请求tag */
50 | protected String mTag = null;
51 | /** url参数 */
52 | protected Map
3 | * Title: DownloadFileRequest.java
4 | * Description: 下载文件请求类
5 | * Copyright: Copyright (c) 2014-2016 gjfax.com
6 | * Company: 广金所
7 | * Author: 罗旭东 (hi@luoxudong.com)
8 | * Date: 2017/1/24 12:12
9 | * Version: 1.0
10 | *
11 | */
12 | package com.luoxudong.app.asynchttp.request;
13 |
14 | import com.luoxudong.app.asynchttp.AsyncHttpTask;
15 | import com.luoxudong.app.asynchttp.builder.DownloadFileBuilder;
16 | import com.luoxudong.app.asynchttp.callable.RequestCallable;
17 | import com.luoxudong.app.asynchttp.handler.DownloadFileResponseHandler;
18 | import com.luoxudong.app.asynchttp.handler.ResponseHandler;
19 |
20 | import okhttp3.Request;
21 |
22 | /**
23 | *
24 | * Class: DownloadFileRequest
25 | * Description: 下载文件请求类
26 | * Author: 罗旭东 (hi@luoxudong.com)
27 | * Date: 2017/1/24 12:12
28 | * Version: 1.0
29 | *
30 | */
31 | public class DownloadFileRequest extends AsyncHttpRequest {
32 | /** 断点下载起始位置 */
33 | private long mOffset = 0;
34 | /** 下载文件大小 */
35 | private long mLength = 0;
36 | /** 下载文件保存路径 */
37 | private String mFileDir = null;
38 | /** 下载文件名 */
39 | private String mFileName = null;
40 |
41 | public DownloadFileRequest(DownloadFileBuilder builder) {
42 | super(builder);
43 | }
44 |
45 | @Override
46 | public AsyncHttpTask build() {
47 | //断点下载
48 | if (mOffset > 0 || mLength > 0) {
49 | String rangeValue = "bytes=" + mOffset + "-";
50 |
51 | if (mLength > 0) {
52 | rangeValue += (mOffset + mLength);
53 | }
54 |
55 | mHeaderParams.put("range", rangeValue);
56 | }
57 |
58 | initRequest();
59 | return new AsyncHttpTask(this);
60 | }
61 |
62 | @Override
63 | public Request buildRequest(RequestCallable callable) {
64 | return mBuilder.get().build();
65 | }
66 |
67 | @Override
68 | public ResponseHandler buildResponseHandler(RequestCallable callable) {
69 | return new DownloadFileResponseHandler(mFileDir, mFileName, mOffset, callable);
70 | }
71 |
72 | public void setOffset(long offset) {
73 | mOffset = offset;
74 | }
75 |
76 | public void setLength(long length) {
77 | mLength = length;
78 | }
79 |
80 | public void setFileDir(String fileDir) {
81 | mFileDir = fileDir;
82 | }
83 |
84 | public void setFileName(String fileName) {
85 | mFileName = fileName;
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/request/GetRequest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Title: GetRequest.java
3 | * Description:
4 | * Copyright: Copyright (c) 2013-2015 luoxudong.com
5 | * Company: 个人
6 | * Author: 罗旭东 (hi@luoxudong.com)
7 | * Date: 2016年10月13日 下午3:44:01
8 | * Version: 1.0
9 | */
10 | package com.luoxudong.app.asynchttp.request;
11 |
12 | import okhttp3.Request;
13 |
14 | import com.luoxudong.app.asynchttp.AsyncHttpTask;
15 | import com.luoxudong.app.asynchttp.builder.GetBuilder;
16 | import com.luoxudong.app.asynchttp.callable.RequestCallable;
17 | import com.luoxudong.app.asynchttp.handler.JsonResponseHandler;
18 | import com.luoxudong.app.asynchttp.handler.ResponseHandler;
19 | import com.luoxudong.app.asynchttp.handler.StringResponseHandler;
20 | import com.luoxudong.app.asynchttp.interceptor.JsonResponseInterceptor;
21 |
22 | /**
23 | *
24 | * ClassName: GetRequest
25 | * Description:Get请求
26 | * Create by: 罗旭东
27 | * Date: 2016年10月13日 下午3:44:01
28 | *
29 | */
30 | public class GetRequest extends AsyncHttpRequest {
31 | /** 返回数据拦截器 */
32 | private JsonResponseInterceptor mResponseInterceptor = null;
33 | /** 返回的json对象类型 */
34 | private Class mResponseClazz = null;
35 |
36 | public GetRequest(GetBuilder builder) {
37 | super(builder);
38 | }
39 |
40 | @Override
41 | public Request buildRequest(RequestCallable callable) {
42 | return mBuilder.get().build();
43 | }
44 |
45 | @Override
46 | public AsyncHttpTask build() {
47 | initRequest();
48 | return new AsyncHttpTask(this);
49 | }
50 |
51 | @Override
52 | public ResponseHandler buildResponseHandler(RequestCallable callable) {
53 | return new JsonResponseHandler(getResponseClazz(), getResponseInterceptor(), callable);
54 | }
55 |
56 | public JsonResponseInterceptor getResponseInterceptor() {
57 | return mResponseInterceptor;
58 | }
59 |
60 | public void setResponseInterceptor(JsonResponseInterceptor responseInterceptor) {
61 | mResponseInterceptor = responseInterceptor;
62 | }
63 |
64 | public Class getResponseClazz() {
65 | return mResponseClazz;
66 | }
67 |
68 | public void setResponseClazz(Class responseClazz) {
69 | mResponseClazz = responseClazz;
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/request/PostBytesRequest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Title: PostBytesRequest.java
3 | * Description:
4 | * Copyright: Copyright (c) 2013-2015 luoxudong.com
5 | * Company: 个人
6 | * Author: 罗旭东 (hi@luoxudong.com)
7 | * Date: 2016年12月29日 下午2:31:03
8 | * Version: 1.0
9 | */
10 | package com.luoxudong.app.asynchttp.request;
11 |
12 | import com.luoxudong.app.asynchttp.AsyncHttpTask;
13 | import com.luoxudong.app.asynchttp.ContentType;
14 | import com.luoxudong.app.asynchttp.builder.PostBytesBuilder;
15 | import com.luoxudong.app.asynchttp.callable.RequestCallable;
16 | import com.luoxudong.app.asynchttp.handler.ResponseHandler;
17 |
18 | import okhttp3.MediaType;
19 | import okhttp3.Request;
20 | import okhttp3.RequestBody;
21 |
22 | /**
23 | *
24 | * ClassName: PostBytesRequest
25 | * Description:提交byte数组请求类
26 | * Create by: 罗旭东
27 | * Date: 2016年12月29日 下午2:31:03
28 | *
29 | */
30 | public class PostBytesRequest extends AsyncHttpRequest {
31 | private byte[] mBuffer = null;
32 |
33 | public PostBytesRequest(PostBytesBuilder builder) {
34 | super(builder);
35 | }
36 |
37 | @Override
38 | public AsyncHttpTask build() {
39 | initRequest();
40 | return new AsyncHttpTask(this);
41 | }
42 |
43 | @Override
44 | public Request buildRequest(RequestCallable callable) {
45 | if (getBuffer() == null) {
46 | mBuffer = new byte[0];
47 | }
48 | return mBuilder.post(RequestBody.create(MediaType.parse(ContentType.octetStream.getValue()), getBuffer())).build();
49 | }
50 |
51 | @Override
52 | public ResponseHandler buildResponseHandler(RequestCallable callable) {
53 | return new ResponseHandler(callable);
54 | }
55 |
56 | public byte[] getBuffer() {
57 | return mBuffer;
58 | }
59 |
60 | public void setBuffer(byte[] buffer) {
61 | mBuffer = buffer;
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/request/PostFormRequest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Title: PostFormRequest.java
3 | * Description:
4 | * Copyright: Copyright (c) 2013-2015 luoxudong.com
5 | * Company: 个人
6 | * Author: 罗旭东 (hi@luoxudong.com)
7 | * Date: 2016年11月23日 上午11:15:45
8 | * Version: 1.0
9 | */
10 | package com.luoxudong.app.asynchttp.request;
11 |
12 | import com.luoxudong.app.asynchttp.AsyncHttpTask;
13 | import com.luoxudong.app.asynchttp.builder.PostFormBuilder;
14 | import com.luoxudong.app.asynchttp.callable.RequestCallable;
15 | import com.luoxudong.app.asynchttp.handler.JsonResponseHandler;
16 | import com.luoxudong.app.asynchttp.handler.ResponseHandler;
17 | import com.luoxudong.app.asynchttp.interceptor.JsonResponseInterceptor;
18 |
19 | import java.util.Map;
20 |
21 | import okhttp3.FormBody;
22 | import okhttp3.Request;
23 |
24 | /**
25 | *
26 | * ClassName: PostFormRequest
27 | * Description:form提交数据请求
28 | * Create by: 罗旭东
29 | * Date: 2016年11月23日 上午11:15:45
30 | *
31 | */
32 | public class PostFormRequest extends AsyncHttpRequest {
33 | protected Map
27 | * ClassName: PostJsonRequest
28 | * Description:提交json数据请求类
29 | * Create by: 罗旭东
30 | * Date: 2016年12月29日 下午4:23:05
31 | *
32 | */
33 | public class PostJsonRequest extends AsyncHttpRequest {
34 | /** 请求对象 */
35 | private Object mReqObj = null;
36 | /** 请求数据拦截器 */
37 | private JsonRequestInterceptor mRequestInterceptor = null;
38 | /** 返回数据拦截器 */
39 | private JsonResponseInterceptor mResponseInterceptor = null;
40 | /** 返回的json对象类型 */
41 | private Class mResponseClazz = null;
42 |
43 | public PostJsonRequest(PostJsonBuilder builder) {
44 | super(builder);
45 | }
46 |
47 | @Override
48 | public AsyncHttpTask build() {
49 | initRequest();
50 | return new AsyncHttpTask(this);
51 | }
52 |
53 | @Override
54 | public Request buildRequest(RequestCallable callable) {
55 | String body = "";
56 |
57 | if (getRequestInterceptor() != null && getReqObj() != null) {//需要拦截处理
58 | body = getRequestInterceptor().convertJsonToObj(getReqObj());
59 | } else if (getReqObj() != null){
60 | body = getReqObj().toString();
61 | }
62 |
63 | return mBuilder.post(RequestBody.create(MediaType.parse(ContentType.text.getValue()), body)).build();
64 | }
65 |
66 | @Override
67 | public ResponseHandler buildResponseHandler(RequestCallable callable) {
68 | return new JsonResponseHandler(getResponseClazz(), getResponseInterceptor(), callable);
69 | }
70 |
71 | public Object getReqObj() {
72 | return mReqObj;
73 | }
74 |
75 | public JsonRequestInterceptor getRequestInterceptor() {
76 | return mRequestInterceptor;
77 | }
78 |
79 | public JsonResponseInterceptor getResponseInterceptor() {
80 | return mResponseInterceptor;
81 | }
82 |
83 | public Class getResponseClazz() {
84 | return mResponseClazz;
85 | }
86 |
87 | public void setReqObj(Object reqObj) {
88 | mReqObj = reqObj;
89 | }
90 |
91 | public void setRequestInterceptor(JsonRequestInterceptor requestInterceptor) {
92 | mRequestInterceptor = requestInterceptor;
93 | }
94 |
95 | public void setResponseInterceptor(JsonResponseInterceptor responseInterceptor) {
96 | mResponseInterceptor = responseInterceptor;
97 | }
98 |
99 | public void setResponseClazz(Class responseClazz) {
100 | mResponseClazz = responseClazz;
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/request/PostRequest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Title: PostRequest.java
3 | * Description:
4 | * Copyright: Copyright (c) 2013-2015 luoxudong.com
5 | * Company: 个人
6 | * Author: 罗旭东 (hi@luoxudong.com)
7 | * Date: 2016年10月13日 下午7:18:22
8 | * Version: 1.0
9 | */
10 | package com.luoxudong.app.asynchttp.request;
11 |
12 | import com.luoxudong.app.asynchttp.AsyncHttpTask;
13 | import com.luoxudong.app.asynchttp.ContentType;
14 | import com.luoxudong.app.asynchttp.builder.PostBuilder;
15 | import com.luoxudong.app.asynchttp.callable.RequestCallable;
16 | import com.luoxudong.app.asynchttp.handler.JsonResponseHandler;
17 | import com.luoxudong.app.asynchttp.handler.ResponseHandler;
18 | import com.luoxudong.app.asynchttp.interceptor.JsonResponseInterceptor;
19 |
20 | import okhttp3.MediaType;
21 | import okhttp3.Request;
22 | import okhttp3.RequestBody;
23 |
24 | /**
25 | *
26 | * ClassName: PostRequest
27 | * Description:POST请求
28 | * Create by: 罗旭东
29 | * Date: 2016年10月13日 下午7:18:22
30 | *
31 | */
32 | public class PostRequest extends AsyncHttpRequest {
33 | private String mBody = null;
34 | private String mContentType = null;
35 | /** 返回数据拦截器 */
36 | private JsonResponseInterceptor mResponseInterceptor = null;
37 | /** 返回的json对象类型 */
38 | private Class mResponseClazz = null;
39 |
40 | public PostRequest(PostBuilder builder) {
41 | super(builder);
42 | }
43 |
44 | @Override
45 | public Request buildRequest(RequestCallable callable) {
46 | if (getContentType() == null) {
47 | setContentType(ContentType.text.getValue());
48 | }
49 |
50 | if (getBody() == null) {
51 | setBody("");
52 | }
53 | return mBuilder.post(RequestBody.create(MediaType.parse(getContentType()), getBody())).build();
54 | }
55 |
56 | @Override
57 | public AsyncHttpTask build() {
58 | initRequest();
59 | return new AsyncHttpTask(this);
60 | }
61 |
62 | @Override
63 | public ResponseHandler buildResponseHandler(RequestCallable callable) {
64 | return new JsonResponseHandler(getResponseClazz(), getResponseInterceptor(), callable);
65 | }
66 |
67 |
68 | public String getBody() {
69 | return mBody;
70 | }
71 |
72 | public void setBody(String body) {
73 | mBody = body;
74 | }
75 |
76 | public String getContentType() {
77 | return mContentType;
78 | }
79 |
80 | public void setContentType(String contentType) {
81 | mContentType = contentType;
82 | }
83 |
84 | public JsonResponseInterceptor getResponseInterceptor() {
85 | return mResponseInterceptor;
86 | }
87 |
88 | public Class getResponseClazz() {
89 | return mResponseClazz;
90 | }
91 |
92 | public void setResponseInterceptor(JsonResponseInterceptor responseInterceptor) {
93 | mResponseInterceptor = responseInterceptor;
94 | }
95 |
96 | public void setResponseClazz(Class responseClazz) {
97 | mResponseClazz = responseClazz;
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/src/main/src/main/java/com/luoxudong/app/asynchttp/request/UploadFileRequest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Title: UploadFileRequest.java
3 | * Description:
4 | * Copyright: Copyright (c) 2013-2015 luoxudong.com
5 | * Company: 个人
6 | * Author: 罗旭东 (hi@luoxudong.com)
7 | * Date: 2016年11月23日 下午5:07:54
8 | * Version: 1.0
9 | */
10 | package com.luoxudong.app.asynchttp.request;
11 |
12 | import com.luoxudong.app.asynchttp.AsyncHttpConst;
13 | import com.luoxudong.app.asynchttp.AsyncHttpTask;
14 | import com.luoxudong.app.asynchttp.ContentType;
15 | import com.luoxudong.app.asynchttp.builder.UploadFileBuilder;
16 | import com.luoxudong.app.asynchttp.callable.RequestCallable;
17 | import com.luoxudong.app.asynchttp.exception.AsyncHttpException;
18 | import com.luoxudong.app.asynchttp.exception.AsyncHttpExceptionCode;
19 | import com.luoxudong.app.asynchttp.handler.ResponseHandler;
20 | import com.luoxudong.app.asynchttp.handler.UploadFileResponseHandler;
21 | import com.luoxudong.app.asynchttp.model.FileWrapper;
22 | import com.luoxudong.app.asynchttp.utils.AsyncHttpLog;
23 |
24 | import java.io.IOException;
25 | import java.io.RandomAccessFile;
26 | import java.util.Map;
27 |
28 | import okhttp3.Headers;
29 | import okhttp3.MediaType;
30 | import okhttp3.MultipartBody;
31 | import okhttp3.Request;
32 | import okhttp3.RequestBody;
33 | import okio.BufferedSink;
34 |
35 | /**
36 | *
37 | * ClassName: UploadFileRequest
38 | * Description:上传文件
39 | * Create by: 罗旭东
40 | * Date: 2016年11月23日 下午5:07:54
41 | *
42 | */
43 | public class UploadFileRequest extends AsyncHttpRequest {
44 | private final String TAG = UploadFileRequest.class.getSimpleName();
45 |
46 | private Map