>();
29 |
30 | static {
31 | blackList.add(HttpException.class);
32 | blackList.add(Callback.CancelledException.class);
33 | blackList.add(MalformedURLException.class);
34 | blackList.add(URISyntaxException.class);
35 | blackList.add(NoRouteToHostException.class);
36 | blackList.add(PortUnreachableException.class);
37 | blackList.add(ProtocolException.class);
38 | blackList.add(NullPointerException.class);
39 | blackList.add(FileNotFoundException.class);
40 | blackList.add(JSONException.class);
41 | blackList.add(UnknownHostException.class);
42 | blackList.add(IllegalArgumentException.class);
43 | }
44 |
45 | public HttpRetryHandler() {
46 | }
47 |
48 | public void setMaxRetryCount(int maxRetryCount) {
49 | this.maxRetryCount = maxRetryCount;
50 | }
51 |
52 | public boolean canRetry(UriRequest request, Throwable ex, int count) {
53 |
54 | LogUtil.w(ex.getMessage(), ex);
55 |
56 | if (count > maxRetryCount) {
57 | LogUtil.w(request.toString());
58 | LogUtil.w("The Max Retry times has been reached!");
59 | return false;
60 | }
61 |
62 | if (!HttpMethod.permitsRetry(request.getParams().getMethod())) {
63 | LogUtil.w(request.toString());
64 | LogUtil.w("The Request Method can not be retried.");
65 | return false;
66 | }
67 |
68 | if (blackList.contains(ex.getClass())) {
69 | LogUtil.w(request.toString());
70 | LogUtil.w("The Exception can not be retried.");
71 | return false;
72 | }
73 |
74 | return true;
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/app/InputStreamResponseParser.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.app;
2 |
3 | import java.io.InputStream;
4 | import java.lang.reflect.Type;
5 |
6 | /**
7 | * Created by wyouflf on 16/2/2.
8 | */
9 | public abstract class InputStreamResponseParser implements ResponseParser {
10 |
11 | public abstract Object parse(Type resultType, Class> resultClass, InputStream result) throws Throwable;
12 |
13 | /**
14 | * Deprecated, see {@link InputStreamResponseParser#parse(Type, Class, InputStream)}
15 | *
16 | * @throws Throwable
17 | */
18 | @Override
19 | @Deprecated
20 | public final Object parse(Type resultType, Class> resultClass, String result) throws Throwable {
21 | return null;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/app/ParamsBuilder.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.app;
2 |
3 | import org.xutils.http.RequestParams;
4 | import org.xutils.http.annotation.HttpRequest;
5 |
6 | import javax.net.ssl.SSLSocketFactory;
7 |
8 | /**
9 | * Created by wyouflf on 15/8/20.
10 | *
11 | * {@link org.xutils.http.annotation.HttpRequest} 注解的参数构建的模板接口
12 | */
13 | public interface ParamsBuilder {
14 |
15 | /**
16 | * 根据@HttpRequest构建请求的url
17 | *
18 | * @param params
19 | * @param httpRequest
20 | * @return
21 | */
22 | String buildUri(RequestParams params, HttpRequest httpRequest) throws Throwable;
23 |
24 | /**
25 | * 根据注解的cacheKeys构建缓存的自定义key,
26 | * 如果返回null, 默认使用 url 和整个 query string 组成.
27 | *
28 | * @param params
29 | * @param cacheKeys
30 | * @return
31 | */
32 | String buildCacheKey(RequestParams params, String[] cacheKeys);
33 |
34 | /**
35 | * 自定义SSLSocketFactory
36 | *
37 | * @return
38 | */
39 | SSLSocketFactory getSSLSocketFactory() throws Throwable;
40 |
41 | /**
42 | * 为请求添加通用参数等操作
43 | *
44 | * @param params
45 | */
46 | void buildParams(RequestParams params) throws Throwable;
47 |
48 | /**
49 | * 自定义参数签名
50 | *
51 | * @param params
52 | * @param signs
53 | */
54 | void buildSign(RequestParams params, String[] signs) throws Throwable;
55 | }
56 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/app/RedirectHandler.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.app;
2 |
3 | import org.xutils.http.RequestParams;
4 | import org.xutils.http.request.UriRequest;
5 |
6 | /**
7 | * Created by wyouflf on 15/11/12.
8 | * 请求重定向控制接口
9 | */
10 | public interface RedirectHandler {
11 |
12 | /**
13 | * 根据请求信息返回自定义重定向的请求参数
14 | *
15 | * @param request
16 | * @return 返回不为null时进行重定向
17 | */
18 | RequestParams getRedirectParams(UriRequest request) throws Throwable;
19 | }
20 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/app/RequestInterceptListener.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.app;
2 |
3 |
4 | import org.xutils.http.request.UriRequest;
5 |
6 | /**
7 | * Created by wyouflf on 15/11/10.
8 | * 拦截请求响应(在后台线程工作).
9 | *
10 | * 用法: 请求的callback参数同时实现RequestInterceptListener
11 | */
12 | public interface RequestInterceptListener {
13 |
14 | void beforeRequest(UriRequest request) throws Throwable;
15 |
16 | void afterRequest(UriRequest request) throws Throwable;
17 | }
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/app/RequestTracker.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.app;
2 |
3 | import org.xutils.http.RequestParams;
4 | import org.xutils.http.request.UriRequest;
5 |
6 | /**
7 | * Created by wyouflf on 15/9/10.
8 | * 请求过程追踪, 适合用来记录请求日志.
9 | * 所有回调方法都在主线程进行.
10 | *
11 | * 用法:
12 | * 1. 将RequestTracker实例设置给请求参数RequestParams.
13 | * 2. 请的callback参数同时实现RequestTracker接口;
14 | * 3. 注册给UriRequestFactory的默认RequestTracker.
15 | * 注意: 请求回调RequestTracker时优先级按照上面的顺序,
16 | * 找到一个RequestTracker的实现会忽略其他.
17 | */
18 | public interface RequestTracker {
19 |
20 | void onWaiting(RequestParams params);
21 |
22 | void onStart(RequestParams params);
23 |
24 | void onRequestCreated(UriRequest request);
25 |
26 | void onCache(UriRequest request, Object result);
27 |
28 | void onSuccess(UriRequest request, Object result);
29 |
30 | void onCancelled(UriRequest request);
31 |
32 | void onError(UriRequest request, Throwable ex, boolean isCallbackError);
33 |
34 | void onFinished(UriRequest request);
35 | }
36 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/app/ResponseParser.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.app;
2 |
3 |
4 | import org.xutils.http.request.UriRequest;
5 |
6 | import java.lang.reflect.Type;
7 |
8 | /**
9 | * Created by wyouflf on 15/8/4.
10 | * {@link org.xutils.http.annotation.HttpResponse} 注解的返回值转换模板
11 | */
12 | public interface ResponseParser {
13 |
14 | /**
15 | * 检查请求相应头等处理
16 | *
17 | * @param request
18 | * @throws Throwable
19 | */
20 | void checkResponse(UriRequest request) throws Throwable;
21 |
22 | /**
23 | * 转换result为resultType类型的对象
24 | *
25 | * @param resultType 返回值类型(可能带有泛型信息)
26 | * @param resultClass 返回值类型
27 | * @param result 字符串数据
28 | * @return
29 | * @throws Throwable
30 | */
31 | Object parse(Type resultType, Class> resultClass, String result) throws Throwable;
32 | }
33 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/body/BodyItemWrapper.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.body;
2 |
3 | import android.text.TextUtils;
4 |
5 | /**
6 | * Created by wyouflf on 15/8/13.
7 | * Wrapper for RequestBody value.
8 | */
9 | public final class BodyItemWrapper {
10 |
11 | private final Object value;
12 | private final String fileName;
13 | private final String contentType;
14 |
15 | public BodyItemWrapper(Object value, String contentType) {
16 | this(value, contentType, null);
17 | }
18 |
19 | public BodyItemWrapper(Object value, String contentType, String fileName) {
20 | this.value = value;
21 | if (TextUtils.isEmpty(contentType)) {
22 | this.contentType = "application/octet-stream";
23 | } else {
24 | this.contentType = contentType;
25 | }
26 | this.fileName = fileName;
27 | }
28 |
29 | public Object getValue() {
30 | return value;
31 | }
32 |
33 | public String getFileName() {
34 | return fileName;
35 | }
36 |
37 | public String getContentType() {
38 | return contentType;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/body/FileBody.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.body;
2 |
3 | import android.text.TextUtils;
4 |
5 | import java.io.File;
6 | import java.io.FileInputStream;
7 | import java.io.IOException;
8 | import java.net.HttpURLConnection;
9 |
10 | /**
11 | * Created by wyouflf on 15/8/13.
12 | */
13 | public class FileBody extends InputStreamBody {
14 |
15 | private File file;
16 | private String contentType;
17 |
18 | public FileBody(File file) throws IOException {
19 | this(file, null);
20 | }
21 |
22 | public FileBody(File file, String contentType) throws IOException {
23 | super(new FileInputStream(file));
24 | this.file = file;
25 | this.contentType = contentType;
26 | }
27 |
28 | @Override
29 | public void setContentType(String contentType) {
30 | this.contentType = contentType;
31 | }
32 |
33 | @Override
34 | public String getContentType() {
35 | if (TextUtils.isEmpty(contentType)) {
36 | contentType = getFileContentType(file);
37 | }
38 | return contentType;
39 | }
40 |
41 | public static String getFileContentType(File file) {
42 | String filename = file.getName();
43 | String contentType = HttpURLConnection.guessContentTypeFromName(filename);
44 | if (TextUtils.isEmpty(contentType)) {
45 | contentType = "application/octet-stream";
46 | } else {
47 | contentType = contentType.replaceFirst("\\/jpg$", "/jpeg");
48 | }
49 | return contentType;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/body/InputStreamBody.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.body;
2 |
3 | import android.text.TextUtils;
4 |
5 | import org.xutils.common.Callback;
6 | import org.xutils.common.util.IOUtil;
7 | import org.xutils.http.ProgressHandler;
8 |
9 | import java.io.ByteArrayInputStream;
10 | import java.io.FileInputStream;
11 | import java.io.IOException;
12 | import java.io.InputStream;
13 | import java.io.OutputStream;
14 |
15 |
16 | /**
17 | * Author: wyouflf
18 | * Time: 2014/05/30
19 | */
20 | public class InputStreamBody implements ProgressBody {
21 |
22 | private InputStream content;
23 | private String contentType;
24 |
25 | private final long total;
26 | private long current = 0;
27 |
28 | private ProgressHandler callBackHandler;
29 |
30 | public InputStreamBody(InputStream inputStream) {
31 | this(inputStream, null);
32 | }
33 |
34 | public InputStreamBody(InputStream inputStream, String contentType) {
35 | this.content = inputStream;
36 | this.contentType = contentType;
37 | this.total = getInputStreamLength(inputStream);
38 | }
39 |
40 | @Override
41 | public void setProgressHandler(ProgressHandler progressHandler) {
42 | this.callBackHandler = progressHandler;
43 | }
44 |
45 | @Override
46 | public long getContentLength() {
47 | return total;
48 | }
49 |
50 | @Override
51 | public void setContentType(String contentType) {
52 | this.contentType = contentType;
53 | }
54 |
55 | @Override
56 | public String getContentType() {
57 | return TextUtils.isEmpty(contentType) ? "application/octet-stream" : contentType;
58 | }
59 |
60 | @Override
61 | public void writeTo(OutputStream out) throws IOException {
62 | if (callBackHandler != null && !callBackHandler.updateProgress(total, current, true)) {
63 | throw new Callback.CancelledException("upload stopped!");
64 | }
65 |
66 | byte[] buffer = new byte[1024];
67 | try {
68 | int len = 0;
69 | while ((len = content.read(buffer)) != -1) {
70 | out.write(buffer, 0, len);
71 | current += len;
72 | if (callBackHandler != null && !callBackHandler.updateProgress(total, current, false)) {
73 | throw new Callback.CancelledException("upload stopped!");
74 | }
75 | }
76 | out.flush();
77 |
78 | if (callBackHandler != null) {
79 | callBackHandler.updateProgress(total, total, true);
80 | }
81 | } finally {
82 | IOUtil.closeQuietly(content);
83 | }
84 | }
85 |
86 | public static long getInputStreamLength(InputStream inputStream) {
87 | try {
88 | if (inputStream instanceof FileInputStream ||
89 | inputStream instanceof ByteArrayInputStream) {
90 | return inputStream.available();
91 | }
92 | } catch (Throwable ignored) {
93 | }
94 | return -1L;
95 | }
96 | }
97 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/body/ProgressBody.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.body;
2 |
3 |
4 | import org.xutils.http.ProgressHandler;
5 |
6 | /**
7 | * Created by wyouflf on 15/8/13.
8 | */
9 | public interface ProgressBody extends RequestBody {
10 | void setProgressHandler(ProgressHandler progressHandler);
11 | }
12 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/body/RequestBody.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.body;
2 |
3 | import java.io.IOException;
4 | import java.io.OutputStream;
5 |
6 | /**
7 | * Created by wyouflf on 15/10/29.
8 | */
9 | public interface RequestBody {
10 |
11 | long getContentLength();
12 |
13 | void setContentType(String contentType);
14 |
15 | String getContentType();
16 |
17 | void writeTo(OutputStream out) throws IOException;
18 | }
19 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/body/StringBody.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.body;
2 |
3 | import android.text.TextUtils;
4 |
5 | import java.io.IOException;
6 | import java.io.OutputStream;
7 | import java.io.UnsupportedEncodingException;
8 |
9 | /**
10 | * Author: wyouflf
11 | * Time: 2014/05/30
12 | */
13 | public class StringBody implements RequestBody {
14 |
15 | private byte[] content;
16 | private String contentType;
17 | private String charset = "UTF-8";
18 |
19 | public StringBody(String str, String charset) throws UnsupportedEncodingException {
20 | if (!TextUtils.isEmpty(charset)) {
21 | this.charset = charset;
22 | }
23 | this.content = str.getBytes(this.charset);
24 | }
25 |
26 | @Override
27 | public long getContentLength() {
28 | return content.length;
29 | }
30 |
31 | @Override
32 | public void setContentType(String contentType) {
33 | this.contentType = contentType;
34 | }
35 |
36 | @Override
37 | public String getContentType() {
38 | return TextUtils.isEmpty(contentType) ? "application/json;charset=" + charset : contentType;
39 | }
40 |
41 | @Override
42 | public void writeTo(OutputStream out) throws IOException {
43 | out.write(content);
44 | out.flush();
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/body/UrlEncodedParamsBody.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.body;
2 |
3 | import android.net.Uri;
4 | import android.text.TextUtils;
5 |
6 | import org.xutils.common.util.KeyValue;
7 |
8 | import java.io.IOException;
9 | import java.io.OutputStream;
10 | import java.util.List;
11 |
12 | /**
13 | * Author: wyouflf
14 | * Time: 2014/05/30
15 | */
16 | public class UrlEncodedParamsBody implements RequestBody {
17 |
18 | private byte[] content;
19 | private String charset = "UTF-8";
20 |
21 | public UrlEncodedParamsBody(List params, String charset) throws IOException {
22 | if (!TextUtils.isEmpty(charset)) {
23 | this.charset = charset;
24 | }
25 | StringBuilder contentSb = new StringBuilder();
26 | if (params != null) {
27 | for (KeyValue kv : params) {
28 | String name = kv.key;
29 | String value = kv.getValueStr();
30 | if (!TextUtils.isEmpty(name) && value != null) {
31 | if (contentSb.length() > 0) {
32 | contentSb.append("&");
33 | }
34 | contentSb.append(Uri.encode(name, this.charset))
35 | .append("=")
36 | .append(Uri.encode(value, this.charset));
37 | }
38 | }
39 | }
40 |
41 | this.content = contentSb.toString().getBytes(this.charset);
42 | }
43 |
44 | @Override
45 | public long getContentLength() {
46 | return content.length;
47 | }
48 |
49 | @Override
50 | public void setContentType(String contentType) {
51 | }
52 |
53 | @Override
54 | public String getContentType() {
55 | return "application/x-www-form-urlencoded;charset=" + charset;
56 | }
57 |
58 | @Override
59 | public void writeTo(OutputStream sink) throws IOException {
60 | sink.write(this.content);
61 | sink.flush();
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/cookie/CookieEntity.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.cookie;
2 |
3 | import android.text.TextUtils;
4 |
5 | import org.xutils.db.annotation.Column;
6 | import org.xutils.db.annotation.Table;
7 |
8 | import java.net.HttpCookie;
9 | import java.net.URI;
10 |
11 | /**
12 | * Created by wyouflf on 15/8/20.
13 | * 数据库中的cookie实体
14 | */
15 | @Table(name = "cookie",
16 | onCreated = "CREATE UNIQUE INDEX index_cookie_unique ON cookie(\"name\",\"domain\",\"path\")")
17 | /*package*/ final class CookieEntity {
18 |
19 | // ~ 100 year
20 | private static final long MAX_EXPIRY = System.currentTimeMillis() + 1000L * 60L * 60L * 24L * 30L * 12L * 100L;
21 |
22 | @Column(name = "id", isId = true)
23 | private long id;
24 |
25 | @Column(name = "uri")
26 | private String uri; // cookie add by this uri.
27 |
28 | @Column(name = "name")
29 | private String name;
30 | @Column(name = "value")
31 | private String value;
32 | @Column(name = "comment")
33 | private String comment;
34 | @Column(name = "commentURL")
35 | private String commentURL;
36 | @Column(name = "discard")
37 | private boolean discard;
38 | @Column(name = "domain")
39 | private String domain;
40 | @Column(name = "expiry")
41 | private long expiry = MAX_EXPIRY;
42 | @Column(name = "path")
43 | private String path;
44 | @Column(name = "portList")
45 | private String portList;
46 | @Column(name = "secure")
47 | private boolean secure;
48 | @Column(name = "version")
49 | private int version = 1;
50 |
51 | public CookieEntity() {
52 | }
53 |
54 | public CookieEntity(URI uri, HttpCookie cookie) {
55 | this.uri = uri == null ? null : uri.toString();
56 | this.name = cookie.getName();
57 | this.value = cookie.getValue();
58 | this.comment = cookie.getComment();
59 | this.commentURL = cookie.getCommentURL();
60 | this.discard = cookie.getDiscard();
61 | this.domain = cookie.getDomain();
62 | long maxAge = cookie.getMaxAge();
63 | if (maxAge != -1L && maxAge > 0) {
64 | this.expiry = (maxAge * 1000L) + System.currentTimeMillis();
65 | if (this.expiry < 0L) { // 计算溢出?
66 | this.expiry = MAX_EXPIRY;
67 | }
68 | } else {
69 | this.expiry = -1L;
70 | }
71 | this.path = cookie.getPath();
72 | if (!TextUtils.isEmpty(path) && path.length() > 1 && path.endsWith("/")) {
73 | this.path = path.substring(0, path.length() - 1);
74 | }
75 | this.portList = cookie.getPortlist();
76 | this.secure = cookie.getSecure();
77 | this.version = cookie.getVersion();
78 | }
79 |
80 | public HttpCookie toHttpCookie() {
81 | HttpCookie cookie = new HttpCookie(name, value);
82 | cookie.setComment(comment);
83 | cookie.setCommentURL(commentURL);
84 | cookie.setDiscard(discard);
85 | cookie.setDomain(domain);
86 | if (expiry == -1L) {
87 | cookie.setMaxAge(-1L);
88 | } else {
89 | cookie.setMaxAge((expiry - System.currentTimeMillis()) / 1000L);
90 | }
91 | cookie.setPath(path);
92 | cookie.setPortlist(portList);
93 | cookie.setSecure(secure);
94 | cookie.setVersion(version);
95 | return cookie;
96 | }
97 |
98 | public long getId() {
99 | return id;
100 | }
101 |
102 | public void setId(long id) {
103 | this.id = id;
104 | }
105 |
106 | public String getUri() {
107 | return uri;
108 | }
109 |
110 | public void setUri(String uri) {
111 | this.uri = uri;
112 | }
113 |
114 | public boolean isExpired() {
115 | return expiry != -1L && expiry < System.currentTimeMillis();
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/loader/BooleanLoader.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.loader;
2 |
3 | import org.xutils.cache.DiskCacheEntity;
4 | import org.xutils.http.request.UriRequest;
5 |
6 | import java.io.InputStream;
7 |
8 | /**
9 | * Author: wyouflf
10 | * Time: 2014/05/30
11 | */
12 | /*package*/ class BooleanLoader extends Loader {
13 |
14 | @Override
15 | public Loader newInstance() {
16 | return new BooleanLoader();
17 | }
18 |
19 | @Override
20 | public Boolean load(final InputStream in) throws Throwable {
21 | return false;
22 | }
23 |
24 | @Override
25 | public Boolean load(final UriRequest request) throws Throwable {
26 | request.sendRequest();
27 | return request.getResponseCode() < 300;
28 | }
29 |
30 | @Override
31 | public Boolean loadFromCache(final DiskCacheEntity cacheEntity) throws Throwable {
32 | return null;
33 | }
34 |
35 | @Override
36 | public void save2Cache(final UriRequest request) {
37 |
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/loader/ByteArrayLoader.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.loader;
2 |
3 | import org.xutils.cache.DiskCacheEntity;
4 | import org.xutils.common.util.IOUtil;
5 | import org.xutils.http.request.UriRequest;
6 |
7 | import java.io.InputStream;
8 |
9 | /**
10 | * Author: wyouflf
11 | * Time: 2014/05/30
12 | */
13 | /*package*/ class ByteArrayLoader extends Loader {
14 |
15 | @Override
16 | public Loader newInstance() {
17 | return new ByteArrayLoader();
18 | }
19 |
20 | @Override
21 | public byte[] load(final InputStream in) throws Throwable {
22 | return IOUtil.readBytes(in);
23 | }
24 |
25 | @Override
26 | public byte[] load(final UriRequest request) throws Throwable {
27 | request.sendRequest();
28 | return this.load(request.getInputStream());
29 | }
30 |
31 | @Override
32 | public byte[] loadFromCache(final DiskCacheEntity cacheEntity) throws Throwable {
33 | return null;
34 | }
35 |
36 | @Override
37 | public void save2Cache(final UriRequest request) {
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/loader/IntegerLoader.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.loader;
2 |
3 | import org.xutils.cache.DiskCacheEntity;
4 | import org.xutils.http.request.UriRequest;
5 |
6 | import java.io.InputStream;
7 |
8 | /**
9 | * @author: wyouflf
10 | * @date: 2014/10/17
11 | */
12 | /*package*/ class IntegerLoader extends Loader {
13 | @Override
14 | public Loader newInstance() {
15 | return new IntegerLoader();
16 | }
17 |
18 | @Override
19 | public Integer load(InputStream in) throws Throwable {
20 | return 100;
21 | }
22 |
23 | @Override
24 | public Integer load(UriRequest request) throws Throwable {
25 | request.sendRequest();
26 | return request.getResponseCode();
27 | }
28 |
29 | @Override
30 | public Integer loadFromCache(final DiskCacheEntity cacheEntity) throws Throwable {
31 | return null;
32 | }
33 |
34 | @Override
35 | public void save2Cache(UriRequest request) {
36 |
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/loader/JSONArrayLoader.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.loader;
2 |
3 | import android.text.TextUtils;
4 |
5 | import org.json.JSONArray;
6 | import org.xutils.cache.DiskCacheEntity;
7 | import org.xutils.common.util.IOUtil;
8 | import org.xutils.http.RequestParams;
9 | import org.xutils.http.request.UriRequest;
10 |
11 | import java.io.InputStream;
12 |
13 | /**
14 | * Author: wyouflf
15 | * Time: 2014/06/16
16 | */
17 | /*package*/ class JSONArrayLoader extends Loader {
18 |
19 | private String charset = "UTF-8";
20 | private String resultStr = null;
21 |
22 | @Override
23 | public Loader newInstance() {
24 | return new JSONArrayLoader();
25 | }
26 |
27 | @Override
28 | public void setParams(final RequestParams params) {
29 | if (params != null) {
30 | String charset = params.getCharset();
31 | if (!TextUtils.isEmpty(charset)) {
32 | this.charset = charset;
33 | }
34 | }
35 | }
36 |
37 | @Override
38 | public JSONArray load(final InputStream in) throws Throwable {
39 | resultStr = IOUtil.readStr(in, charset);
40 | return new JSONArray(resultStr);
41 | }
42 |
43 | @Override
44 | public JSONArray load(final UriRequest request) throws Throwable {
45 | request.sendRequest();
46 | return this.load(request.getInputStream());
47 | }
48 |
49 | @Override
50 | public JSONArray loadFromCache(final DiskCacheEntity cacheEntity) throws Throwable {
51 | if (cacheEntity != null) {
52 | String text = cacheEntity.getTextContent();
53 | if (!TextUtils.isEmpty(text)) {
54 | return new JSONArray(text);
55 | }
56 | }
57 |
58 | return null;
59 | }
60 |
61 | @Override
62 | public void save2Cache(UriRequest request) {
63 | saveStringCache(request, resultStr);
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/loader/JSONObjectLoader.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.loader;
2 |
3 | import android.text.TextUtils;
4 |
5 | import org.json.JSONObject;
6 | import org.xutils.cache.DiskCacheEntity;
7 | import org.xutils.common.util.IOUtil;
8 | import org.xutils.http.RequestParams;
9 | import org.xutils.http.request.UriRequest;
10 |
11 | import java.io.InputStream;
12 |
13 | /**
14 | * Author: wyouflf
15 | * Time: 2014/06/16
16 | */
17 | /*package*/ class JSONObjectLoader extends Loader {
18 |
19 | private String charset = "UTF-8";
20 | private String resultStr = null;
21 |
22 | @Override
23 | public Loader newInstance() {
24 | return new JSONObjectLoader();
25 | }
26 |
27 | @Override
28 | public void setParams(final RequestParams params) {
29 | if (params != null) {
30 | String charset = params.getCharset();
31 | if (!TextUtils.isEmpty(charset)) {
32 | this.charset = charset;
33 | }
34 | }
35 | }
36 |
37 | @Override
38 | public JSONObject load(final InputStream in) throws Throwable {
39 | resultStr = IOUtil.readStr(in, charset);
40 | return new JSONObject(resultStr);
41 | }
42 |
43 | @Override
44 | public JSONObject load(final UriRequest request) throws Throwable {
45 | request.sendRequest();
46 | return this.load(request.getInputStream());
47 | }
48 |
49 | @Override
50 | public JSONObject loadFromCache(final DiskCacheEntity cacheEntity) throws Throwable {
51 | if (cacheEntity != null) {
52 | String text = cacheEntity.getTextContent();
53 | if (!TextUtils.isEmpty(text)) {
54 | return new JSONObject(text);
55 | }
56 | }
57 |
58 | return null;
59 | }
60 |
61 | @Override
62 | public void save2Cache(UriRequest request) {
63 | saveStringCache(request, resultStr);
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/loader/Loader.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.loader;
2 |
3 |
4 | import android.text.TextUtils;
5 |
6 | import org.xutils.cache.DiskCacheEntity;
7 | import org.xutils.cache.LruDiskCache;
8 | import org.xutils.http.ProgressHandler;
9 | import org.xutils.http.RequestParams;
10 | import org.xutils.http.request.UriRequest;
11 |
12 | import java.io.InputStream;
13 | import java.util.Date;
14 |
15 | /**
16 | * Author: wyouflf
17 | * Time: 2014/05/26
18 | */
19 | public abstract class Loader {
20 |
21 | protected RequestParams params;
22 | protected ProgressHandler progressHandler;
23 |
24 | public void setParams(final RequestParams params) {
25 | this.params = params;
26 | }
27 |
28 | public void setProgressHandler(final ProgressHandler callbackHandler) {
29 | this.progressHandler = callbackHandler;
30 | }
31 |
32 | protected void saveStringCache(UriRequest request, String resultStr) {
33 | if (!TextUtils.isEmpty(resultStr)) {
34 | DiskCacheEntity entity = new DiskCacheEntity();
35 | entity.setKey(request.getCacheKey());
36 | entity.setLastAccess(System.currentTimeMillis());
37 | entity.setEtag(request.getETag());
38 | entity.setExpires(request.getExpiration());
39 | entity.setLastModify(new Date(request.getLastModified()));
40 | entity.setTextContent(resultStr);
41 | LruDiskCache.getDiskCache(request.getParams().getCacheDirName()).put(entity);
42 | }
43 | }
44 |
45 | public abstract Loader newInstance();
46 |
47 | public abstract T load(final InputStream in) throws Throwable;
48 |
49 | public abstract T load(final UriRequest request) throws Throwable;
50 |
51 | public abstract T loadFromCache(final DiskCacheEntity cacheEntity) throws Throwable;
52 |
53 | public abstract void save2Cache(final UriRequest request);
54 | }
55 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/loader/LoaderFactory.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.loader;
2 |
3 |
4 | import org.json.JSONArray;
5 | import org.json.JSONObject;
6 | import org.xutils.http.RequestParams;
7 |
8 | import java.io.File;
9 | import java.lang.reflect.Type;
10 | import java.util.HashMap;
11 |
12 | /**
13 | * Author: wyouflf
14 | * Time: 2014/05/26
15 | */
16 | public final class LoaderFactory {
17 |
18 | private LoaderFactory() {
19 | }
20 |
21 | /**
22 | * key: loadType
23 | */
24 | private static final HashMap converterHashMap = new HashMap();
25 |
26 | static {
27 | converterHashMap.put(JSONObject.class, new JSONObjectLoader());
28 | converterHashMap.put(JSONArray.class, new JSONArrayLoader());
29 | converterHashMap.put(String.class, new StringLoader());
30 | converterHashMap.put(File.class, new FileLoader());
31 | converterHashMap.put(byte[].class, new ByteArrayLoader());
32 | BooleanLoader booleanLoader = new BooleanLoader();
33 | converterHashMap.put(boolean.class, booleanLoader);
34 | converterHashMap.put(Boolean.class, booleanLoader);
35 | IntegerLoader integerLoader = new IntegerLoader();
36 | converterHashMap.put(int.class, integerLoader);
37 | converterHashMap.put(Integer.class, integerLoader);
38 | }
39 |
40 | @SuppressWarnings("unchecked")
41 | public static Loader> getLoader(Type type, RequestParams params) {
42 | Loader> result = converterHashMap.get(type);
43 | if (result == null) {
44 | result = new ObjectLoader(type);
45 | } else {
46 | result = result.newInstance();
47 | }
48 | result.setParams(params);
49 | return result;
50 | }
51 |
52 | public static void registerLoader(Type type, Loader loader) {
53 | converterHashMap.put(type, loader);
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/loader/StringLoader.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.loader;
2 |
3 | import android.text.TextUtils;
4 |
5 | import org.xutils.cache.DiskCacheEntity;
6 | import org.xutils.common.util.IOUtil;
7 | import org.xutils.http.RequestParams;
8 | import org.xutils.http.request.UriRequest;
9 |
10 | import java.io.InputStream;
11 |
12 | /**
13 | * Author: wyouflf
14 | * Time: 2014/05/30
15 | */
16 | /*package*/ class StringLoader extends Loader {
17 |
18 | private String charset = "UTF-8";
19 | private String resultStr = null;
20 |
21 | @Override
22 | public Loader newInstance() {
23 | return new StringLoader();
24 | }
25 |
26 | @Override
27 | public void setParams(final RequestParams params) {
28 | if (params != null) {
29 | String charset = params.getCharset();
30 | if (!TextUtils.isEmpty(charset)) {
31 | this.charset = charset;
32 | }
33 | }
34 | }
35 |
36 | @Override
37 | public String load(final InputStream in) throws Throwable {
38 | resultStr = IOUtil.readStr(in, charset);
39 | return resultStr;
40 | }
41 |
42 | @Override
43 | public String load(final UriRequest request) throws Throwable {
44 | request.sendRequest();
45 | return this.load(request.getInputStream());
46 | }
47 |
48 | @Override
49 | public String loadFromCache(final DiskCacheEntity cacheEntity) throws Throwable {
50 | if (cacheEntity != null) {
51 | return cacheEntity.getTextContent();
52 | }
53 |
54 | return null;
55 | }
56 |
57 | @Override
58 | public void save2Cache(UriRequest request) {
59 | saveStringCache(request, resultStr);
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/request/AssetsRequest.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.request;
2 |
3 | import org.xutils.cache.DiskCacheEntity;
4 | import org.xutils.cache.LruDiskCache;
5 | import org.xutils.common.util.IOUtil;
6 | import org.xutils.common.util.LogUtil;
7 | import org.xutils.http.RequestParams;
8 | import org.xutils.x;
9 |
10 | import java.io.File;
11 | import java.io.IOException;
12 | import java.io.InputStream;
13 | import java.lang.reflect.Type;
14 | import java.util.Date;
15 | import java.util.List;
16 | import java.util.Map;
17 |
18 | /**
19 | * Created by wyouflf on 15/11/4.
20 | * Assets资源文件请求
21 | */
22 | public class AssetsRequest extends UriRequest {
23 |
24 | private long contentLength = 0;
25 | private InputStream inputStream;
26 |
27 | public AssetsRequest(RequestParams params, Type loadType) throws Throwable {
28 | super(params, loadType);
29 | }
30 |
31 | @Override
32 | public void sendRequest() throws Throwable {
33 |
34 | }
35 |
36 | @Override
37 | public boolean isLoading() {
38 | return true;
39 | }
40 |
41 | @Override
42 | public String getCacheKey() {
43 | return queryUrl;
44 | }
45 |
46 | @Override
47 | public Object loadResult() throws Throwable {
48 | return this.loader.load(this);
49 | }
50 |
51 | @Override
52 | public Object loadResultFromCache() throws Throwable {
53 | DiskCacheEntity cacheEntity = LruDiskCache.getDiskCache(params.getCacheDirName())
54 | .setMaxSize(params.getCacheSize())
55 | .get(this.getCacheKey());
56 |
57 | if (cacheEntity != null) {
58 | Date lastModifiedDate = cacheEntity.getLastModify();
59 | if (lastModifiedDate == null || lastModifiedDate.getTime() < getAssetsLastModified()) {
60 | return null;
61 | }
62 | return loader.loadFromCache(cacheEntity);
63 | } else {
64 | return null;
65 | }
66 | }
67 |
68 | @Override
69 | public void clearCacheHeader() {
70 |
71 | }
72 |
73 | @Override
74 | public InputStream getInputStream() throws IOException {
75 | if (inputStream == null) {
76 | if (callingClassLoader != null) {
77 | String assetsPath = "assets/" + queryUrl.substring("assets://".length());
78 | inputStream = callingClassLoader.getResourceAsStream(assetsPath);
79 | contentLength = inputStream.available();
80 | }
81 | }
82 | return inputStream;
83 | }
84 |
85 | @Override
86 | public void close() throws IOException {
87 | IOUtil.closeQuietly(inputStream);
88 | inputStream = null;
89 | }
90 |
91 | @Override
92 | public long getContentLength() {
93 | try {
94 | getInputStream();
95 | return contentLength;
96 | } catch (Throwable ex) {
97 | LogUtil.e(ex.getMessage(), ex);
98 | }
99 | return 0;
100 | }
101 |
102 | @Override
103 | public int getResponseCode() throws IOException {
104 | return getInputStream() != null ? 200 : 404;
105 | }
106 |
107 | @Override
108 | public String getResponseMessage() throws IOException {
109 | return null;
110 | }
111 |
112 | @Override
113 | public long getExpiration() {
114 | return Long.MAX_VALUE;
115 | }
116 |
117 | @Override
118 | public long getLastModified() {
119 | return getAssetsLastModified();
120 | }
121 |
122 | @Override
123 | public String getETag() {
124 | return null;
125 | }
126 |
127 | @Override
128 | public String getResponseHeader(String name) {
129 | return null;
130 | }
131 |
132 | @Override
133 | public Map> getResponseHeaders() {
134 | return null;
135 | }
136 |
137 | @Override
138 | public long getHeaderFieldDate(String name, long defaultValue) {
139 | return defaultValue;
140 | }
141 |
142 | /**
143 | * 如果你的应用基于插件架构, 并且插件有独立的资源管理实现, 可能需要覆盖这里的实现方式,
144 | * 并在UriRequestFactory中注册你的实现.
145 | */
146 | protected long getAssetsLastModified() {
147 | return new File(x.app().getApplicationInfo().sourceDir).lastModified();
148 | }
149 |
150 | }
151 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/request/LocalFileRequest.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.request;
2 |
3 | import org.xutils.common.util.IOUtil;
4 | import org.xutils.http.RequestParams;
5 | import org.xutils.http.loader.FileLoader;
6 |
7 | import java.io.File;
8 | import java.io.FileInputStream;
9 | import java.io.IOException;
10 | import java.io.InputStream;
11 | import java.lang.reflect.Type;
12 | import java.util.List;
13 | import java.util.Map;
14 |
15 | /**
16 | * Created by wyouflf on 15/11/4.
17 | * 本地文件请求
18 | */
19 | public class LocalFileRequest extends UriRequest {
20 |
21 | private InputStream inputStream;
22 |
23 | LocalFileRequest(RequestParams params, Type loadType) throws Throwable {
24 | super(params, loadType);
25 | }
26 |
27 | @Override
28 | public void sendRequest() throws Throwable {
29 |
30 | }
31 |
32 | @Override
33 | public boolean isLoading() {
34 | return true;
35 | }
36 |
37 | @Override
38 | public String getCacheKey() {
39 | return null;
40 | }
41 |
42 | @Override
43 | public Object loadResult() throws Throwable {
44 | if (loader instanceof FileLoader) {
45 | return getFile();
46 | }
47 | return this.loader.load(this);
48 | }
49 |
50 | @Override
51 | public Object loadResultFromCache() throws Throwable {
52 | return null;
53 | }
54 |
55 | @Override
56 | public void clearCacheHeader() {
57 |
58 | }
59 |
60 | @Override
61 | public void save2Cache() {
62 |
63 | }
64 |
65 | private File getFile() {
66 | String filePath = null;
67 | if (queryUrl.startsWith("file:")) {
68 | filePath = queryUrl.substring("file:".length());
69 | } else {
70 | filePath = queryUrl;
71 | }
72 | // filePath开始位置多余的"/"或被自动去掉
73 | return new File(filePath);
74 | }
75 |
76 | @Override
77 | public InputStream getInputStream() throws IOException {
78 | if (inputStream == null) {
79 | inputStream = new FileInputStream(getFile());
80 | }
81 | return inputStream;
82 | }
83 |
84 | @Override
85 | public void close() throws IOException {
86 | IOUtil.closeQuietly(inputStream);
87 | inputStream = null;
88 | }
89 |
90 | @Override
91 | public long getContentLength() {
92 | return getFile().length();
93 | }
94 |
95 | @Override
96 | public int getResponseCode() throws IOException {
97 | return getFile().exists() ? 200 : 404;
98 | }
99 |
100 | @Override
101 | public String getResponseMessage() throws IOException {
102 | return null;
103 | }
104 |
105 | @Override
106 | public long getExpiration() {
107 | return -1;
108 | }
109 |
110 | @Override
111 | public long getLastModified() {
112 | return getFile().lastModified();
113 | }
114 |
115 | @Override
116 | public String getETag() {
117 | return null;
118 | }
119 |
120 | @Override
121 | public String getResponseHeader(String name) {
122 | return null;
123 | }
124 |
125 | @Override
126 | public Map> getResponseHeaders() {
127 | return null;
128 | }
129 |
130 | @Override
131 | public long getHeaderFieldDate(String name, long defaultValue) {
132 | return defaultValue;
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/request/UriRequest.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.request;
2 |
3 | import org.xutils.common.util.LogUtil;
4 | import org.xutils.http.ProgressHandler;
5 | import org.xutils.http.RequestParams;
6 | import org.xutils.http.app.RequestInterceptListener;
7 | import org.xutils.http.loader.Loader;
8 | import org.xutils.http.loader.LoaderFactory;
9 | import org.xutils.x;
10 |
11 | import java.io.Closeable;
12 | import java.io.IOException;
13 | import java.io.InputStream;
14 | import java.lang.reflect.Type;
15 | import java.util.List;
16 | import java.util.Map;
17 |
18 | /**
19 | * Created by wyouflf on 15/7/23.
20 | * Uri请求发送和数据接收
21 | */
22 | public abstract class UriRequest implements Closeable {
23 |
24 | protected final String queryUrl;
25 | protected final RequestParams params;
26 | protected final Loader> loader;
27 |
28 | protected ClassLoader callingClassLoader = null;
29 | protected ProgressHandler progressHandler = null;
30 | protected RequestInterceptListener requestInterceptListener = null;
31 |
32 | /*package*/ UriRequest(RequestParams params, Type loadType) throws Throwable {
33 | this.params = params;
34 | this.queryUrl = buildQueryUrl(params);
35 | this.loader = LoaderFactory.getLoader(loadType, params);
36 | }
37 |
38 | // build query
39 | protected String buildQueryUrl(RequestParams params) {
40 | return params.getUri();
41 | }
42 |
43 | public void setProgressHandler(ProgressHandler progressHandler) {
44 | this.progressHandler = progressHandler;
45 | this.loader.setProgressHandler(progressHandler);
46 | }
47 |
48 | public void setCallingClassLoader(ClassLoader callingClassLoader) {
49 | this.callingClassLoader = callingClassLoader;
50 | }
51 |
52 | public void setRequestInterceptListener(RequestInterceptListener requestInterceptListener) {
53 | this.requestInterceptListener = requestInterceptListener;
54 | }
55 |
56 | public RequestParams getParams() {
57 | return params;
58 | }
59 |
60 | public String getRequestUri() {
61 | return queryUrl;
62 | }
63 |
64 | /**
65 | * invoke via Loader
66 | *
67 | * @throws IOException
68 | */
69 | public abstract void sendRequest() throws Throwable;
70 |
71 | public abstract boolean isLoading();
72 |
73 | public abstract String getCacheKey();
74 |
75 | /**
76 | * 由loader发起请求, 拿到结果.
77 | *
78 | * @return
79 | * @throws Throwable
80 | */
81 | public Object loadResult() throws Throwable {
82 | return this.loader.load(this);
83 | }
84 |
85 | /**
86 | * 尝试从缓存获取结果, 并为请求头加入缓存控制参数.
87 | *
88 | * @return
89 | * @throws Throwable
90 | */
91 | public abstract Object loadResultFromCache() throws Throwable;
92 |
93 | public abstract void clearCacheHeader();
94 |
95 | public void save2Cache() {
96 | x.task().run(new Runnable() {
97 | @Override
98 | public void run() {
99 | try {
100 | loader.save2Cache(UriRequest.this);
101 | } catch (Throwable ex) {
102 | LogUtil.e(ex.getMessage(), ex);
103 | }
104 | }
105 | });
106 | }
107 |
108 | public abstract InputStream getInputStream() throws IOException;
109 |
110 | @Override
111 | public abstract void close() throws IOException;
112 |
113 | public abstract long getContentLength();
114 |
115 | public abstract int getResponseCode() throws IOException;
116 |
117 | public abstract String getResponseMessage() throws IOException;
118 |
119 | public abstract long getExpiration();
120 |
121 | public abstract long getLastModified();
122 |
123 | public abstract String getETag();
124 |
125 | public abstract String getResponseHeader(String name);
126 |
127 | public abstract Map> getResponseHeaders();
128 |
129 | public abstract long getHeaderFieldDate(String name, long defaultValue);
130 |
131 | @Override
132 | public String toString() {
133 | return getRequestUri();
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/http/request/UriRequestFactory.java:
--------------------------------------------------------------------------------
1 | package org.xutils.http.request;
2 |
3 | import android.text.TextUtils;
4 |
5 | import org.xutils.common.util.LogUtil;
6 | import org.xutils.http.RequestParams;
7 | import org.xutils.http.app.RequestTracker;
8 |
9 | import java.lang.reflect.Constructor;
10 | import java.lang.reflect.Type;
11 | import java.util.HashMap;
12 |
13 | /**
14 | * Created by wyouflf on 15/11/4.
15 | * Uri请求创建工厂
16 | */
17 | public final class UriRequestFactory {
18 |
19 | private static Class extends RequestTracker> defaultTrackerCls;
20 |
21 | private static final HashMap>
22 | SCHEME_CLS_MAP = new HashMap>();
23 |
24 | private UriRequestFactory() {
25 | }
26 |
27 | public static UriRequest getUriRequest(RequestParams params, Type loadType) throws Throwable {
28 |
29 | // get scheme
30 | String scheme = null;
31 | String uri = params.getUri();
32 | int index = uri.indexOf(":");
33 | if (index > 0) {
34 | scheme = uri.substring(0, index);
35 | } else if (uri.startsWith("/")) {
36 | scheme = "file";
37 | }
38 |
39 | // get UriRequest
40 | if (!TextUtils.isEmpty(scheme)) {
41 | Class extends UriRequest> cls = SCHEME_CLS_MAP.get(scheme);
42 | if (cls != null) {
43 | Constructor extends UriRequest> constructor
44 | = cls.getConstructor(RequestParams.class, Class.class);
45 | return constructor.newInstance(params, loadType);
46 | } else {
47 | if (scheme.startsWith("http")) {
48 | return new HttpRequest(params, loadType);
49 | } else if (scheme.equals("assets")) {
50 | return new AssetsRequest(params, loadType);
51 | } else if (scheme.equals("file")) {
52 | return new LocalFileRequest(params, loadType);
53 | } else {
54 | throw new IllegalArgumentException("The url not be support: " + uri);
55 | }
56 | }
57 | } else {
58 | throw new IllegalArgumentException("The url not be support: " + uri);
59 | }
60 | }
61 |
62 | public static void registerDefaultTrackerClass(Class extends RequestTracker> trackerCls) {
63 | UriRequestFactory.defaultTrackerCls = trackerCls;
64 | }
65 |
66 | public static RequestTracker getDefaultTracker() {
67 | try {
68 | return defaultTrackerCls == null ? null : defaultTrackerCls.newInstance();
69 | } catch (Throwable ex) {
70 | LogUtil.e(ex.getMessage(), ex);
71 | }
72 | return null;
73 | }
74 |
75 | public static void registerRequestClass(String scheme, Class extends UriRequest> uriRequestCls) {
76 | SCHEME_CLS_MAP.put(scheme, uriRequestCls);
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/image/GifDrawable.java:
--------------------------------------------------------------------------------
1 | package org.xutils.image;
2 |
3 | import android.graphics.Canvas;
4 | import android.graphics.ColorFilter;
5 | import android.graphics.Movie;
6 | import android.graphics.PixelFormat;
7 | import android.graphics.drawable.Animatable;
8 | import android.graphics.drawable.Drawable;
9 | import android.os.SystemClock;
10 |
11 | import org.xutils.common.util.LogUtil;
12 |
13 | public class GifDrawable extends Drawable implements Runnable, Animatable {
14 |
15 | private int byteCount;
16 | private int rate = 300;
17 | private volatile boolean running;
18 |
19 | private final Movie movie;
20 | private final int duration;
21 | private final long begin = SystemClock.uptimeMillis();
22 |
23 | public GifDrawable(Movie movie, int byteCount) {
24 | this.movie = movie;
25 | this.byteCount = byteCount;
26 | this.duration = movie.duration();
27 | }
28 |
29 | public int getDuration() {
30 | return duration;
31 | }
32 |
33 | public Movie getMovie() {
34 | return movie;
35 | }
36 |
37 | public int getByteCount() {
38 | if (byteCount == 0) {
39 | byteCount = (movie.width() * movie.height() * 3) * (5/*fake frame count*/);
40 | }
41 | return byteCount;
42 | }
43 |
44 | public int getRate() {
45 | return rate;
46 | }
47 |
48 | public void setRate(int rate) {
49 | this.rate = rate;
50 | }
51 |
52 | @Override
53 | public void draw(Canvas canvas) {
54 | try {
55 | int time = duration > 0 ? (int) (SystemClock.uptimeMillis() - begin) % duration : 0;
56 | movie.setTime(time);
57 | movie.draw(canvas, 0, 0);
58 | start();
59 | } catch (Throwable ex) {
60 | LogUtil.e(ex.getMessage(), ex);
61 | }
62 | }
63 |
64 | @Override
65 | public void start() {
66 | if (!isRunning()) {
67 | running = true;
68 | run();
69 | }
70 | }
71 |
72 | @Override
73 | public void stop() {
74 | if (isRunning()) {
75 | this.unscheduleSelf(this);
76 | }
77 | }
78 |
79 | @Override
80 | public boolean isRunning() {
81 | return running && duration > 0;
82 | }
83 |
84 | @Override
85 | public void run() {
86 | if (duration > 0) {
87 | this.invalidateSelf();
88 | this.scheduleSelf(this, SystemClock.uptimeMillis() + rate);
89 | }
90 | }
91 |
92 | @Override
93 | public void setAlpha(int alpha) {
94 |
95 | }
96 |
97 | @Override
98 | public int getIntrinsicWidth() {
99 | return movie.width();
100 | }
101 |
102 | @Override
103 | public int getIntrinsicHeight() {
104 | return movie.height();
105 | }
106 |
107 | @Override
108 | public void setColorFilter(ColorFilter cf) {
109 | }
110 |
111 | @Override
112 | public int getOpacity() {
113 | return movie.isOpaque() ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT;
114 | }
115 |
116 | }
117 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/image/ImageAnimationHelper.java:
--------------------------------------------------------------------------------
1 | package org.xutils.image;
2 |
3 | import android.graphics.drawable.Drawable;
4 | import android.view.animation.AlphaAnimation;
5 | import android.view.animation.Animation;
6 | import android.view.animation.DecelerateInterpolator;
7 | import android.widget.ImageView;
8 |
9 | import org.xutils.common.util.LogUtil;
10 |
11 | import java.lang.reflect.Method;
12 |
13 | /**
14 | * Created by wyouflf on 15/10/13.
15 | * ImageView Animation Helper
16 | */
17 | public final class ImageAnimationHelper {
18 |
19 | private final static Method cloneMethod;
20 |
21 | static {
22 | Method method = null;
23 | try {
24 | method = Animation.class.getDeclaredMethod("clone");
25 | method.setAccessible(true);
26 | } catch (Throwable ex) {
27 | method = null;
28 | LogUtil.w(ex.getMessage(), ex);
29 | }
30 | cloneMethod = method;
31 | }
32 |
33 | private ImageAnimationHelper() {
34 | }
35 |
36 | public static void fadeInDisplay(final ImageView imageView, Drawable drawable) {
37 | AlphaAnimation fadeAnimation = new AlphaAnimation(0F, 1F);
38 | fadeAnimation.setDuration(300);
39 | fadeAnimation.setInterpolator(new DecelerateInterpolator());
40 | imageView.setImageDrawable(drawable);
41 | imageView.startAnimation(fadeAnimation);
42 | }
43 |
44 | public static void animationDisplay(ImageView imageView, Drawable drawable, Animation animation) {
45 | imageView.setImageDrawable(drawable);
46 | if (cloneMethod != null && animation != null) {
47 | try {
48 | imageView.startAnimation((Animation) cloneMethod.invoke(animation));
49 | } catch (Throwable ex) {
50 | imageView.startAnimation(animation);
51 | }
52 | } else {
53 | imageView.startAnimation(animation);
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/image/ImageManagerImpl.java:
--------------------------------------------------------------------------------
1 | package org.xutils.image;
2 |
3 | import android.graphics.drawable.Drawable;
4 | import android.widget.ImageView;
5 |
6 | import org.xutils.ImageManager;
7 | import org.xutils.common.Callback;
8 | import org.xutils.x;
9 |
10 | import java.io.File;
11 |
12 | /**
13 | * Created by wyouflf on 15/10/9.
14 | */
15 | public final class ImageManagerImpl implements ImageManager {
16 |
17 | private static final Object lock = new Object();
18 | private static volatile ImageManagerImpl instance;
19 |
20 | private ImageManagerImpl() {
21 | }
22 |
23 | public static void registerInstance() {
24 | if (instance == null) {
25 | synchronized (lock) {
26 | if (instance == null) {
27 | instance = new ImageManagerImpl();
28 | }
29 | }
30 | }
31 | x.Ext.setImageManager(instance);
32 | }
33 |
34 |
35 | @Override
36 | public void bind(final ImageView view, final String url) {
37 | x.task().autoPost(new Runnable() {
38 | @Override
39 | public void run() {
40 | ImageLoader.doBind(view, url, null, null);
41 | }
42 | });
43 | }
44 |
45 | @Override
46 | public void bind(final ImageView view, final String url, final ImageOptions options) {
47 | x.task().autoPost(new Runnable() {
48 | @Override
49 | public void run() {
50 | ImageLoader.doBind(view, url, options, null);
51 | }
52 | });
53 | }
54 |
55 | @Override
56 | public void bind(final ImageView view, final String url, final Callback.CommonCallback callback) {
57 | x.task().autoPost(new Runnable() {
58 | @Override
59 | public void run() {
60 | ImageLoader.doBind(view, url, null, callback);
61 | }
62 | });
63 | }
64 |
65 | @Override
66 | public void bind(final ImageView view, final String url, final ImageOptions options, final Callback.CommonCallback callback) {
67 | x.task().autoPost(new Runnable() {
68 | @Override
69 | public void run() {
70 | ImageLoader.doBind(view, url, options, callback);
71 | }
72 | });
73 | }
74 |
75 | @Override
76 | public Callback.Cancelable loadDrawable(String url, ImageOptions options, Callback.CommonCallback callback) {
77 | return ImageLoader.doLoadDrawable(url, options, callback);
78 | }
79 |
80 | @Override
81 | public Callback.Cancelable loadFile(String url, ImageOptions options, Callback.CacheCallback callback) {
82 | return ImageLoader.doLoadFile(url, options, callback);
83 | }
84 |
85 | @Override
86 | public void clearMemCache() {
87 | ImageLoader.clearMemCache();
88 | }
89 |
90 | @Override
91 | public void clearCacheFiles() {
92 | ImageLoader.clearCacheFiles();
93 | ImageDecoder.clearCacheFiles();
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/image/MemCacheKey.java:
--------------------------------------------------------------------------------
1 | package org.xutils.image;
2 |
3 | /**
4 | * Created by wyouflf on 15/10/20.
5 | */
6 | /*package*/ final class MemCacheKey {
7 | public final String url;
8 | public final ImageOptions options;
9 |
10 | public MemCacheKey(String url, ImageOptions options) {
11 | this.url = url;
12 | this.options = options;
13 | }
14 |
15 | @Override
16 | public boolean equals(Object o) {
17 | if (this == o) return true;
18 | if (o == null || getClass() != o.getClass()) return false;
19 |
20 | MemCacheKey that = (MemCacheKey) o;
21 |
22 | if (!url.equals(that.url)) return false;
23 | return options.equals(that.options);
24 |
25 | }
26 |
27 | @Override
28 | public int hashCode() {
29 | int result = url.hashCode();
30 | result = 31 * result + options.hashCode();
31 | return result;
32 | }
33 |
34 | @Override
35 | public String toString() {
36 | return url + options.toString();
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/image/ReusableBitmapDrawable.java:
--------------------------------------------------------------------------------
1 | package org.xutils.image;
2 |
3 | import android.content.res.Resources;
4 | import android.graphics.Bitmap;
5 | import android.graphics.drawable.BitmapDrawable;
6 |
7 | /*package*/ final class ReusableBitmapDrawable extends BitmapDrawable implements ReusableDrawable {
8 |
9 | private MemCacheKey key;
10 |
11 | public ReusableBitmapDrawable(Resources res, Bitmap bitmap) {
12 | super(res, bitmap);
13 | }
14 |
15 | @Override
16 | public MemCacheKey getMemCacheKey() {
17 | return key;
18 | }
19 |
20 | @Override
21 | public void setMemCacheKey(MemCacheKey key) {
22 | this.key = key;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/image/ReusableDrawable.java:
--------------------------------------------------------------------------------
1 | package org.xutils.image;
2 |
3 | /**
4 | * Created by wyouflf on 15/10/20.
5 | * 使已被LruCache移除, 但还在被ImageView使用的Drawable可以再次被回收使用.
6 | */
7 | /*package*/ interface ReusableDrawable {
8 |
9 | MemCacheKey getMemCacheKey();
10 |
11 | void setMemCacheKey(MemCacheKey key);
12 | }
13 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/view/ViewFinder.java:
--------------------------------------------------------------------------------
1 | package org.xutils.view;
2 |
3 | import android.app.Activity;
4 | import android.view.View;
5 |
6 | /**
7 | * Author: wyouflf
8 | * Date: 13-9-9
9 | * Time: 下午12:29
10 | */
11 | /*package*/ final class ViewFinder {
12 |
13 | private View view;
14 | private Activity activity;
15 |
16 | public ViewFinder(View view) {
17 | this.view = view;
18 | }
19 |
20 | public ViewFinder(Activity activity) {
21 | this.activity = activity;
22 | }
23 |
24 | public View findViewById(int id) {
25 | if (view != null) return view.findViewById(id);
26 | if (activity != null) return activity.findViewById(id);
27 | return null;
28 | }
29 |
30 | public View findViewByInfo(ViewInfo info) {
31 | return findViewById(info.value, info.parentId);
32 | }
33 |
34 | public View findViewById(int id, int pid) {
35 | View pView = null;
36 | if (pid > 0) {
37 | pView = this.findViewById(pid);
38 | }
39 |
40 | View view = null;
41 | if (pView != null) {
42 | view = pView.findViewById(id);
43 | } else {
44 | view = this.findViewById(id);
45 | }
46 | return view;
47 | }
48 |
49 | /*public Context getContext() {
50 | if (view != null) return view.getContext();
51 | if (activity != null) return activity;
52 | return null;
53 | }*/
54 | }
55 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/view/ViewInfo.java:
--------------------------------------------------------------------------------
1 | package org.xutils.view;
2 |
3 | /**
4 | * Author: wyouflf
5 | * Date: 13-12-5
6 | * Time: 下午11:25
7 | */
8 | /*package*/ final class ViewInfo {
9 | public int value;
10 | public int parentId;
11 |
12 | @Override
13 | public boolean equals(Object o) {
14 | if (this == o) return true;
15 | if (o == null || getClass() != o.getClass()) return false;
16 |
17 | ViewInfo viewInfo = (ViewInfo) o;
18 |
19 | if (value != viewInfo.value) return false;
20 | return parentId == viewInfo.parentId;
21 |
22 | }
23 |
24 | @Override
25 | public int hashCode() {
26 | int result = value;
27 | result = 31 * result + parentId;
28 | return result;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/view/annotation/ContentView.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2013. wyouflf (wyouflf@gmail.com)
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 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS,
11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | * See the License for the specific language governing permissions and
13 | * limitations under the License.
14 | */
15 |
16 | package org.xutils.view.annotation;
17 |
18 | import java.lang.annotation.ElementType;
19 | import java.lang.annotation.Retention;
20 | import java.lang.annotation.RetentionPolicy;
21 | import java.lang.annotation.Target;
22 |
23 | @Target(ElementType.TYPE)
24 | @Retention(RetentionPolicy.RUNTIME)
25 | public @interface ContentView {
26 | int value();
27 | }
28 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/view/annotation/Event.java:
--------------------------------------------------------------------------------
1 | package org.xutils.view.annotation;
2 |
3 | import android.view.View;
4 |
5 | import java.lang.annotation.ElementType;
6 | import java.lang.annotation.Retention;
7 | import java.lang.annotation.RetentionPolicy;
8 | import java.lang.annotation.Target;
9 |
10 | /**
11 | * 事件注解.
12 | * 被注解的方法必须具备以下形式:
13 | * 1. private 修饰
14 | * 2. 返回值类型没有要求
15 | * 3. 参数签名和type的接口要求的参数签名一致.
16 | * Author: wyouflf
17 | * Date: 13-9-9
18 | * Time: 下午12:43
19 | */
20 | @Target(ElementType.METHOD)
21 | @Retention(RetentionPolicy.RUNTIME)
22 | public @interface Event {
23 |
24 | /**
25 | * 控件的id集合, id小于1时不执行ui事件绑定.
26 | *
27 | * @return
28 | */
29 | int[] value();
30 |
31 | /**
32 | * 控件的parent控件的id集合, 组合为(value[i], parentId[i] or 0).
33 | *
34 | * @return
35 | */
36 | int[] parentId() default 0;
37 |
38 | /**
39 | * 事件的listener, 默认为点击事件.
40 | *
41 | * @return
42 | */
43 | Class> type() default View.OnClickListener.class;
44 |
45 | /**
46 | * 事件的setter方法名, 默认为set+type#simpleName.
47 | *
48 | * @return
49 | */
50 | String setter() default "";
51 |
52 | /**
53 | * 如果type的接口类型提供多个方法, 需要使用此参数指定方法名.
54 | *
55 | * @return
56 | */
57 | String method() default "";
58 | }
59 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/view/annotation/ViewInject.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2013. wyouflf (wyouflf@gmail.com)
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 | * Unless required by applicable law or agreed to in writing, software
10 | * distributed under the License is distributed on an "AS IS" BASIS,
11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | * See the License for the specific language governing permissions and
13 | * limitations under the License.
14 | */
15 |
16 | package org.xutils.view.annotation;
17 |
18 | import java.lang.annotation.ElementType;
19 | import java.lang.annotation.Retention;
20 | import java.lang.annotation.RetentionPolicy;
21 | import java.lang.annotation.Target;
22 |
23 | @Target(ElementType.FIELD)
24 | @Retention(RetentionPolicy.RUNTIME)
25 | public @interface ViewInject {
26 |
27 | int value();
28 |
29 | /* parent view id */
30 | int parentId() default 0;
31 | }
32 |
--------------------------------------------------------------------------------
/xutils/src/main/java/org/xutils/x.java:
--------------------------------------------------------------------------------
1 | package org.xutils;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 |
6 | import org.xutils.common.TaskController;
7 | import org.xutils.common.task.TaskControllerImpl;
8 | import org.xutils.db.DbManagerImpl;
9 | import org.xutils.http.HttpManagerImpl;
10 | import org.xutils.image.ImageManagerImpl;
11 | import org.xutils.view.ViewInjectorImpl;
12 |
13 | import java.lang.reflect.Method;
14 |
15 | import javax.net.ssl.HostnameVerifier;
16 | import javax.net.ssl.HttpsURLConnection;
17 |
18 |
19 | /**
20 | * Created by wyouflf on 15/6/10.
21 | * 任务控制中心, http, image, db, view注入等接口的入口.
22 | * 需要在在application的onCreate中初始化: x.Ext.init(this);
23 | */
24 | public final class x {
25 |
26 | private x() {
27 | }
28 |
29 | public static boolean isDebug() {
30 | return Ext.debug;
31 | }
32 |
33 | public static Application app() {
34 | if (Ext.app == null) {
35 | try {
36 | // 在IDE进行布局预览时使用
37 | Class> renderActionClass = Class.forName("com.android.layoutlib.bridge.impl.RenderAction");
38 | Method method = renderActionClass.getDeclaredMethod("getCurrentContext");
39 | Context context = (Context) method.invoke(null);
40 | Ext.app = new MockApplication(context);
41 | } catch (Throwable ignored) {
42 | throw new RuntimeException("please invoke x.Ext.init(app) on Application#onCreate()"
43 | + " and register your Application in manifest.");
44 | }
45 | }
46 | return Ext.app;
47 | }
48 |
49 | public static TaskController task() {
50 | return Ext.taskController;
51 | }
52 |
53 | public static HttpManager http() {
54 | if (Ext.httpManager == null) {
55 | HttpManagerImpl.registerInstance();
56 | }
57 | return Ext.httpManager;
58 | }
59 |
60 | public static ImageManager image() {
61 | if (Ext.imageManager == null) {
62 | ImageManagerImpl.registerInstance();
63 | }
64 | return Ext.imageManager;
65 | }
66 |
67 | public static ViewInjector view() {
68 | if (Ext.viewInjector == null) {
69 | ViewInjectorImpl.registerInstance();
70 | }
71 | return Ext.viewInjector;
72 | }
73 |
74 | public static DbManager getDb(DbManager.DaoConfig daoConfig) {
75 | return DbManagerImpl.getInstance(daoConfig);
76 | }
77 |
78 | public static class Ext {
79 | private static boolean debug;
80 | private static Application app;
81 | private static TaskController taskController;
82 | private static HttpManager httpManager;
83 | private static ImageManager imageManager;
84 | private static ViewInjector viewInjector;
85 |
86 | private Ext() {
87 | }
88 |
89 | public static void init(Application app) {
90 | TaskControllerImpl.registerInstance();
91 | if (Ext.app == null) {
92 | Ext.app = app;
93 | }
94 | }
95 |
96 | public static void setDebug(boolean debug) {
97 | Ext.debug = debug;
98 | }
99 |
100 | public static void setTaskController(TaskController taskController) {
101 | if (Ext.taskController == null) {
102 | Ext.taskController = taskController;
103 | }
104 | }
105 |
106 | public static void setHttpManager(HttpManager httpManager) {
107 | Ext.httpManager = httpManager;
108 | }
109 |
110 | public static void setImageManager(ImageManager imageManager) {
111 | Ext.imageManager = imageManager;
112 | }
113 |
114 | public static void setViewInjector(ViewInjector viewInjector) {
115 | Ext.viewInjector = viewInjector;
116 | }
117 |
118 | public static void setDefaultHostnameVerifier(HostnameVerifier hostnameVerifier) {
119 | HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
120 | }
121 | }
122 |
123 | private static class MockApplication extends Application {
124 | public MockApplication(Context baseContext) {
125 | this.attachBaseContext(baseContext);
126 | }
127 | }
128 | }
129 |
--------------------------------------------------------------------------------