,可用于实现多文件上传
48 | *
49 | * Part标志上文的内容可以是富媒体形势,比如上传一张图片,上传一段音乐,即它多用于字节流传输。
50 | * 而Filed则相对简单些,通常是字符串键值对。
51 | *
52 | * Part标志上文的内容可以是富媒体形势,比如上传一张图片,上传一段音乐,即它多用于字节流传输。
53 | * 而Filed则相对简单些,通常是字符串键值对。
54 | * @Path 用于url中的占位符,{占位符}和PATH只用在URL的path部分,url中的参数使用Query和QueryMap代替,保证接口定义的简洁
55 | * @Query 用于Get中指定参数
56 | * @QueryMap 和Query使用类似
57 | * @Url 指定请求路径
58 | */
59 |
60 | @GET
61 | Call requestByGet(@Url String url);
62 |
63 | @GET
64 | Call requestByGetAddToken(@Header("token") String token, @Url String url);
65 |
66 | @GET
67 | Call requestByGetAddHeaders(@HeaderMap Map mapHeaders, @Url String url);
68 |
69 | /**
70 | * 文件下载
71 | *
72 | * @param fileUrl
73 | * @return
74 | */
75 | @Streaming
76 | @GET
77 | Call downloadFileByCall(@Url String fileUrl);
78 |
79 | /**
80 | * 这里需要注意的是如果下载的文件较大,比如在10m以上,那么强烈建议你使用@Streaming进行注解,否则将会出现IO异常.
81 | *
82 | * @param fileUrl
83 | * @return
84 | */
85 | @Streaming
86 | @GET
87 | Observable downloadFileByObservable(@Url String fileUrl);
88 |
89 |
90 |
91 | //使用@Headers添加多个请求头
92 | /*@Headers({
93 | "User-Agent:android",
94 | "apikey:123456789",
95 | })*/
96 |
97 | @POST()
98 | Call requestByPostByQueryMap(@Url String url, @QueryMap Map map);
99 |
100 | @POST()
101 | Call requestByPostByQueryMap(@Header("token") String token,@Url String url, @QueryMap Map map);
102 |
103 | @POST()
104 | Call requestByPostByQueryMap(@HeaderMap Map mapHeaders,@Url String url, @QueryMap Map map);
105 |
106 | /**
107 | * 很多情况下,我们需要上传json格式的数据。比如当我们注册新用户的时候,因为用户注册时的数据相对较多,
108 | * 并可能以后会变化,这时候,服务端可能要求我们上传json格式的数据。此时就要@Body注解来实现。
109 | * 直接传入实体,它会自行转化成Json
110 | */
111 | @POST()
112 | Call requestByPost(@Url String url, @Body Object objectBean);
113 |
114 | @POST()
115 | Call requestByPost(@Header("token") String token,@Url String url, @Body Object objectBean);
116 |
117 | @POST()
118 | Call requestByPost(@HeaderMap Map mapHeaders,@Url String url, @Body Object objectBean);
119 |
120 | /**
121 | * 单张图片上传
122 | * retrofit 2.0的上传和以前略有不同,需要借助@Multipart注解、@Part和MultipartBody实现。
123 | *
124 | * @param url
125 | * @param file
126 | * @return
127 | */
128 | @Multipart
129 | @POST()
130 | Call uploadSingleFile(@Url String url, @Part MultipartBody.Part file);
131 |
132 | /**
133 | * 多张图片上传
134 | *
135 | * @param map
136 | * @return
137 | */
138 | @Multipart
139 | @POST()
140 | Call uploadMutipleFiles(@Url String url,@PartMap Map map);
141 |
142 | /**
143 | * 图文混传
144 | */
145 | @Multipart
146 | @POST()
147 | Call uploadMutipleFilesAndBean(@Url String url,@Body Object objectBean, @PartMap Map map);
148 |
149 |
150 | @POST()
151 | @FormUrlEncoded
152 | Observable requestByPostByFieldMap(@Url String url,@FieldMap Map maps);
153 |
154 | @POST()
155 | @FormUrlEncoded
156 | Observable requestByPostByFieldMap(@Header("token") String token,@Url String url,@FieldMap Map maps);
157 |
158 | @POST()
159 | @FormUrlEncoded
160 | Observable requestByPostByFieldMap(@HeaderMap Map mapHeaders,@Url String url,@FieldMap Map maps);
161 | /**
162 | *表明是一个表单格式的请求(Content-Type:application/x-www-form-urlencoded)
163 | * Field("username")
表示将后面的 String name
中name的取值作为 username 的值
164 | */
165 | @POST()
166 | @FormUrlEncoded
167 | Call submitByForm(@Url String url,@Field("name1") Object name1, @Field("name2") Object name2);
168 |
169 | @POST()
170 | @FormUrlEncoded
171 | Call submitByForm(@Header("token") String token,@Url String url,@Field("name1") Object name1, @Field("name2") Object name2);
172 |
173 | @POST()
174 | @FormUrlEncoded
175 | Call submitByForm(@HeaderMap Map mapHeaders,@Url String url,@Field("name1") Object name1, @Field("name2") Object name2);
176 | /**
177 | * {@link Part} 后面支持三种类型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意类型
178 | * 除 {@link okhttp3.MultipartBody.Part} 以外,其它类型都必须带上表单字段({@link okhttp3.MultipartBody.Part} 中已经包含了表单字段的信息),
179 | */
180 | @POST()
181 | @Multipart
182 | Call submitByForm(@Url String url,@Part("name1") RequestBody name1, @Part("name2") RequestBody name2, @Part MultipartBody.Part file);
183 |
184 | @POST()
185 | @FormUrlEncoded
186 | Call submitByFormByFieldMap(@Url String url,@FieldMap Map map);
187 |
188 | @POST()
189 | @FormUrlEncoded
190 | Call submitByFormByFieldMap(@Header("token") String token,@Url String url,@FieldMap Map map);
191 |
192 | @POST()
193 | @FormUrlEncoded
194 | Call submitByFormByFieldMap(@HeaderMap Map mapHeaders,@Url String url,@FieldMap Map map);
195 | /**
196 | * PartMap 注解支持一个Map作为参数,支持 {@link RequestBody } 类型,
197 | * 如果有其它的类型,会被{@link retrofit2.Converter}转换,如后面会介绍的 使用{@link com.google.gson.Gson} 的 {@link retrofit2.converter.gson.GsonRequestBodyConverter}
198 | * 所以{@link MultipartBody.Part} 就不适用了,所以文件只能用 @Part MultipartBody.Part
199 | */
200 | @POST()
201 | @Multipart
202 | Call submitByForm(@Url String url,@PartMap Map args, @Part MultipartBody.Part file);
203 |
204 | @POST()
205 | @Multipart
206 | Call submitByFormByPartMap(@Url String url,@PartMap Map args);
207 |
208 | @POST()
209 | @Multipart
210 | Call submitByFormByPartMap(@Header("token") String token,@Url String url,@PartMap Map args);
211 |
212 | @POST()
213 | @Multipart
214 | Call submitByFormByPartMap(@HeaderMap Map mapHeaders,@Url String url,@PartMap Map args);
215 |
216 |
217 | // 上传单个文件
218 | @Multipart
219 | @POST("upload")
220 | Call uploadSingleFile(
221 | @Part("description") RequestBody description,
222 | @Part MultipartBody.Part file);
223 |
224 | // 上传多个文件
225 | @Multipart
226 | @POST("upload")
227 | Call uploadDoubleFiles(
228 | @Part("description") RequestBody description,
229 | @Part MultipartBody.Part file1,
230 | @Part MultipartBody.Part file2);
231 |
232 |
233 | // 上传多个文件
234 | @Multipart
235 | @POST("upload")
236 | Call uploadMultipleFiles(
237 | @Part("description") RequestBody description,
238 | @Part MultipartBody.Part []files);
239 | }
240 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/retrofit/LogInterceptor.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.retrofit;
2 |
3 | import android.util.Log;
4 |
5 | import java.io.IOException;
6 |
7 | import okhttp3.Interceptor;
8 | import okhttp3.Request;
9 |
10 | public class LogInterceptor implements Interceptor {
11 | @Override
12 | public okhttp3.Response intercept(Chain chain) throws IOException {
13 | Request request = chain.request();
14 |
15 | long t1 = System.nanoTime();
16 | Log.d("OkHttp", "HttpHelper1" + String.format("Sending request %s on %s%n%s",
17 | request.url(), chain.connection(), request.headers()));
18 |
19 | okhttp3.Response response = chain.proceed(request);
20 | long t2 = System.nanoTime();
21 |
22 | Log.d("OkHttp", "HttpHelper2" + String.format("Received response for %s in %.1fms%n%s",
23 | response.request().url(), (t2 - t1) / 1e6d, response.headers()));
24 | return response;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/retrofit/LoggingInterceptor.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.retrofit;
2 |
3 | import android.util.Log;
4 |
5 | import okhttp3.logging.HttpLoggingInterceptor;
6 |
7 | public class LoggingInterceptor {
8 | public static HttpLoggingInterceptor getHttpLoggingInterceptor() {
9 | HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(
10 | new HttpLoggingInterceptor.Logger() {
11 |
12 | @Override
13 | public void log(String message) {
14 | Log.e("OkHttp", "log = " + message);
15 | }
16 |
17 | });
18 | loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
19 | return loggingInterceptor;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/retrofit/RetrofitByGet.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.retrofit;
2 |
3 | import android.database.Observable;
4 | import android.net.Uri;
5 | import android.support.annotation.NonNull;
6 | import android.util.Log;
7 |
8 | import com.google.gson.Gson;
9 |
10 | import java.io.File;
11 | import java.util.Map;
12 |
13 | import okhttp3.MediaType;
14 | import okhttp3.MultipartBody;
15 | import okhttp3.RequestBody;
16 | import okhttp3.ResponseBody;
17 | import retrofit2.Call;
18 | import retrofit2.Callback;
19 | import retrofit2.Retrofit;
20 | import retrofit2.converter.gson.GsonConverterFactory;
21 |
22 | public class RetrofitByGet {
23 |
24 | public static void requestByGet(String url, Callback callback) {
25 |
26 | //步骤4:创建Retrofit对象
27 | Retrofit retrofit = new Retrofit.Builder()
28 | .baseUrl(url)
29 | .addConverterFactory(GsonConverterFactory.create())
30 | .build();
31 |
32 | // 步骤5:创建 网络请求接口 的实例
33 | GetRequestInterface request = retrofit.create(GetRequestInterface.class);
34 | Call call = request.requestByGet(url);
35 |
36 | //步骤6:发送网络请求(异步)
37 | call.enqueue(callback);
38 | }
39 |
40 |
41 | public static void requestByGetAddToken(String token,String url, Callback callback) {
42 |
43 | //步骤4:创建Retrofit对象
44 | Retrofit retrofit = new Retrofit.Builder()
45 | .baseUrl(url)
46 | .addConverterFactory(GsonConverterFactory.create())
47 | .build();
48 |
49 | // 步骤5:创建 网络请求接口 的实例
50 | GetRequestInterface request = retrofit.create(GetRequestInterface.class);
51 | Call call = request.requestByGetAddToken(token,url);
52 |
53 | //步骤6:发送网络请求(异步)
54 | call.enqueue(callback);
55 | }
56 |
57 | public static void requestByGetAddHeaders(Map mapHeaders,String url, Callback callback) {
58 |
59 | //步骤4:创建Retrofit对象
60 | Retrofit retrofit = new Retrofit.Builder()
61 | .baseUrl(url)
62 | .addConverterFactory(GsonConverterFactory.create())
63 | .build();
64 |
65 | // 步骤5:创建 网络请求接口 的实例
66 | GetRequestInterface request = retrofit.create(GetRequestInterface.class);
67 | Call call = request.requestByGetAddHeaders(mapHeaders,url);
68 |
69 | //步骤6:发送网络请求(异步)
70 | call.enqueue(callback);
71 | }
72 |
73 |
74 | //文件下载by call
75 | public static void downloadFileByCall(String url, Callback callback) {
76 |
77 | //步骤4:创建Retrofit对象
78 | Retrofit retrofit = new Retrofit.Builder()
79 | .baseUrl(url)
80 | .addConverterFactory(GsonConverterFactory.create())
81 | .build();
82 |
83 | // 步骤5:创建 网络请求接口 的实例
84 | GetRequestInterface request = retrofit.create(GetRequestInterface.class);
85 | Call call = request.downloadFileByCall(url);
86 |
87 | //步骤6:发送网络请求(异步)
88 | call.enqueue(callback);
89 | }
90 |
91 | //文件下载by Observable
92 | public static Observable downloadFileByObservable(String url, Callback callback) {
93 |
94 | //步骤4:创建Retrofit对象
95 | Retrofit retrofit = new Retrofit.Builder()
96 | .baseUrl(url)
97 | .addConverterFactory(GsonConverterFactory.create())
98 | .build();
99 | GetRequestInterface request = retrofit.create(GetRequestInterface.class);
100 | Observable observable=request.downloadFileByObservable(url);
101 | return observable;
102 | }
103 |
104 |
105 | }
106 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/rxjava/RxJavaByPost.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.rxjava;
2 |
3 | import android.app.Activity;
4 |
5 | import com.tamic.novate.BaseSubscriber;
6 | import com.tamic.novate.Novate;
7 | import com.tamic.novate.callback.RxListCallback;
8 | import com.tamic.novate.callback.RxStringCallback;
9 |
10 | import java.util.List;
11 | import java.util.Map;
12 |
13 | import okhttp3.ResponseBody;
14 | import rx.Observable;
15 | import rx.Observer;
16 |
17 | public class RxJavaByPost {
18 |
19 | /*
20 | Novate构建方法及参数含义:
21 | novate = new Novate.Builder(this)
22 | .addHeader(headers) //添加公共请求头
23 | .addParameters(parameters)//公共参数
24 | .connectTimeout(10) //连接时间 可以忽略
25 | .readTimeout(10) //读取 可以忽略
26 | .addCookie(false) //是否同步cooike 默认不同步
27 | .addCache(true) //是否缓存 默认缓存
28 | .addCache(cache, cacheTime) //自定义缓存
29 | .baseUrl("Url") //base URL
30 | .addLog(true) //是否开启log
31 | .cookieManager(new NovateCookieManager()) // 自定义cooike,可以忽略
32 | .addInterceptor() // 自定义Interceptor
33 | .addNetworkInterceptor() // 自定义NetworkInterceptor
34 | .proxy(proxy) // 设置代理
35 | .client(client) //clent 默认不需要
36 | .build();
37 | */
38 |
39 | public static void PostString(final Activity activity,final String baseUrl, final String urlPath,final Map parameter, final RxStringCallback rxStringCallback) {
40 |
41 | Novate novate = new Novate.Builder(activity)
42 | .baseUrl(baseUrl)
43 | .addCookie(false) //是否同步cooike 默认不同步
44 | .addCache(false) //是否缓存 默认缓存
45 | .addLog(true)
46 | .connectTimeout(500000)
47 | .writeTimeout(500000)
48 | .build();
49 | novate.rxPost(urlPath, parameter, rxStringCallback);
50 | }
51 |
52 | public static void PostStringCookie(final Activity activity,final String baseUrl, final String urlPath,final Map parameter, final RxStringCallback rxStringCallback) {
53 |
54 | Novate novate = new Novate.Builder(activity)
55 | .baseUrl(baseUrl)
56 | .addCookie(true) //是否同步cooike 默认不同步
57 | .addCache(false) //是否缓存 默认缓存
58 | .addLog(true)
59 | .connectTimeout(500000)
60 | .writeTimeout(500000)
61 | .build();
62 | novate.rxPost(urlPath, parameter, rxStringCallback);
63 | }
64 |
65 | public static void PostStringCache(final Activity activity,final String baseUrl, final String urlPath,final Map parameter, final RxStringCallback rxStringCallback) {
66 |
67 | Novate novate = new Novate.Builder(activity)
68 | .baseUrl(baseUrl)
69 | .addCookie(false) //是否同步cooike 默认不同步
70 | .addCache(true) //是否缓存 默认缓存
71 | .addLog(true)
72 | .connectTimeout(500000)
73 | .writeTimeout(500000)
74 | .build();
75 | novate.rxPost(urlPath, parameter, rxStringCallback);
76 | }
77 |
78 | public static void PostStringCookieCache(final Activity activity,final String baseUrl, final String urlPath,final Map parameter, final RxStringCallback rxStringCallback) {
79 |
80 | Novate novate = new Novate.Builder(activity)
81 | .baseUrl(baseUrl)
82 | .addCookie(true) //是否同步cooike 默认不同步
83 | .addCache(true) //是否缓存 默认缓存
84 | .addLog(true)
85 | .connectTimeout(500000)
86 | .writeTimeout(500000)
87 | .build();
88 | novate.rxPost(urlPath, parameter, rxStringCallback);
89 | }
90 |
91 | public static void PostStringAddHeaders(final Activity activity,final String baseUrl, final String urlPath, final Map headers,final Map parameter, final RxStringCallback rxStringCallback) {
92 |
93 | Novate novate = new Novate.Builder(activity)
94 | .baseUrl(baseUrl)
95 | .addHeader(headers)//添加公共请求头
96 | .addCookie(false) //是否同步cooike 默认不同步
97 | .addCache(false) //是否缓存 默认缓存
98 | .addLog(true)
99 | .connectTimeout(500000)
100 | .writeTimeout(500000)
101 | .build();
102 | novate.rxPost(urlPath, parameter, rxStringCallback);
103 | }
104 | public static void PostStringAddHeadersCookie(final Activity activity,final String baseUrl, final String urlPath, final Map headers,final Map parameter, final RxStringCallback rxStringCallback) {
105 |
106 | Novate novate = new Novate.Builder(activity)
107 | .baseUrl(baseUrl)
108 | .addHeader(headers)//添加公共请求头
109 | .addCookie(true) //是否同步cooike 默认不同步
110 | .addCache(false) //是否缓存 默认缓存
111 | .addLog(true)
112 | .connectTimeout(500000)
113 | .writeTimeout(500000)
114 | .build();
115 | novate.rxPost(urlPath, parameter, rxStringCallback);
116 | }
117 |
118 | public static void PostStringAddHeadersCache(final Activity activity,final String baseUrl, final String urlPath, final Map headers,final Map parameter, final RxStringCallback rxStringCallback) {
119 |
120 | Novate novate = new Novate.Builder(activity)
121 | .baseUrl(baseUrl)
122 | .addHeader(headers)//添加公共请求头
123 | .addCookie(false) //是否同步cooike 默认不同步
124 | .addCache(true) //是否缓存 默认缓存
125 | .addLog(true)
126 | .connectTimeout(500000)
127 | .writeTimeout(500000)
128 | .build();
129 | novate.rxPost(urlPath, parameter, rxStringCallback);
130 | }
131 |
132 | public static void PostStringAddHeadersCookieCache(final Activity activity,final String baseUrl, final String urlPath, final Map headers,final Map parameter, final RxStringCallback rxStringCallback) {
133 |
134 | Novate novate = new Novate.Builder(activity)
135 | .baseUrl(baseUrl)
136 | .addHeader(headers)//添加公共请求头
137 | .addCookie(true) //是否同步cooike 默认不同步
138 | .addCache(true) //是否缓存 默认缓存
139 | .addLog(true)
140 | .connectTimeout(500000)
141 | .writeTimeout(500000)
142 | .build();
143 | novate.rxPost(urlPath, parameter, rxStringCallback);
144 | }
145 |
146 |
147 | public static void PostList(Activity activity,String baseUrl, String pathUrl,Map parameter, RxListCallback> rxListCallback) {
148 |
149 | Novate novate = new Novate.Builder(activity)
150 | .baseUrl(baseUrl)
151 | .addCookie(false) //是否同步cooike 默认不同步
152 | .addCache(false) //是否缓存 默认缓存
153 | .addLog(true)
154 | .connectTimeout(500000)
155 | .writeTimeout(500000)
156 | .build();
157 | novate.rxPost(pathUrl, parameter, rxListCallback );
158 | }
159 | public static void PostListCookie(Activity activity,String baseUrl, String pathUrl,Map parameter, RxListCallback> rxListCallback) {
160 |
161 | Novate novate = new Novate.Builder(activity)
162 | .baseUrl(baseUrl)
163 | .addCookie(true) //是否同步cooike 默认不同步
164 | .addCache(false) //是否缓存 默认缓存
165 | .addLog(true)
166 | .connectTimeout(500000)
167 | .writeTimeout(500000)
168 | .build();
169 | novate.rxPost(pathUrl, parameter, rxListCallback );
170 | }
171 | public static void PostListCache(Activity activity,String baseUrl, String pathUrl,Map parameter, RxListCallback> rxListCallback) {
172 |
173 | Novate novate = new Novate.Builder(activity)
174 | .baseUrl(baseUrl)
175 | .addCookie(false) //是否同步cooike 默认不同步
176 | .addCache(true) //是否缓存 默认缓存
177 | .addLog(true)
178 | .connectTimeout(500000)
179 | .writeTimeout(500000)
180 | .build();
181 | novate.rxPost(pathUrl, parameter, rxListCallback );
182 | }
183 | public static void PostListCookieCache(Activity activity,String baseUrl, String pathUrl,Map parameter, RxListCallback> rxListCallback) {
184 |
185 | Novate novate = new Novate.Builder(activity)
186 | .baseUrl(baseUrl)
187 | .addCookie(true) //是否同步cooike 默认不同步
188 | .addCache(true) //是否缓存 默认缓存
189 | .addLog(true)
190 | .connectTimeout(500000)
191 | .writeTimeout(500000)
192 | .build();
193 | novate.rxPost(pathUrl, parameter, rxListCallback );
194 | }
195 |
196 |
197 |
198 | public static void PostListAddHeaders(Activity activity,String baseUrl, String pathUrl, final Map headers,Map parameter, RxListCallback> rxListCallback) {
199 |
200 | Novate novate = new Novate.Builder(activity)
201 | .baseUrl(baseUrl)
202 | .addHeader(headers)//添加公共请求头
203 | .addCookie(false) //是否同步cooike 默认不同步
204 | .addCache(false) //是否缓存 默认缓存
205 | .addLog(true)
206 | .connectTimeout(500000)
207 | .writeTimeout(500000)
208 | .build();
209 | novate.rxPost(pathUrl, parameter, rxListCallback );
210 | }
211 |
212 | public static void PostListAddHeadersCookie(Activity activity,String baseUrl, String pathUrl, final Map headers,Map parameter, RxListCallback> rxListCallback) {
213 |
214 | Novate novate = new Novate.Builder(activity)
215 | .baseUrl(baseUrl)
216 | .addHeader(headers)//添加公共请求头
217 | .addCookie(true) //是否同步cooike 默认不同步
218 | .addCache(false) //是否缓存 默认缓存
219 | .addLog(true)
220 | .connectTimeout(500000)
221 | .writeTimeout(500000)
222 | .build();
223 | novate.rxPost(pathUrl, parameter, rxListCallback );
224 | }
225 |
226 | public static void PostListAddHeadersCache(Activity activity,String baseUrl, String pathUrl, final Map headers,Map parameter, RxListCallback> rxListCallback) {
227 |
228 | Novate novate = new Novate.Builder(activity)
229 | .baseUrl(baseUrl)
230 | .addHeader(headers)//添加公共请求头
231 | .addCookie(false) //是否同步cooike 默认不同步
232 | .addCache(true) //是否缓存 默认缓存
233 | .addLog(true)
234 | .connectTimeout(500000)
235 | .writeTimeout(500000)
236 | .build();
237 | novate.rxPost(pathUrl, parameter, rxListCallback );
238 | }
239 |
240 | public static void PostListAddHeadersCookieCache(Activity activity,String baseUrl, String pathUrl, final Map headers,Map parameter, RxListCallback> rxListCallback) {
241 |
242 | Novate novate = new Novate.Builder(activity)
243 | .baseUrl(baseUrl)
244 | .addHeader(headers)//添加公共请求头
245 | .addCookie(true) //是否同步cooike 默认不同步
246 | .addCache(true) //是否缓存 默认缓存
247 | .addLog(true)
248 | .connectTimeout(500000)
249 | .writeTimeout(500000)
250 | .build();
251 | novate.rxPost(pathUrl, parameter, rxListCallback );
252 | }
253 |
254 |
255 | public static void requestByBody(final Activity activity,final String baseUrl, final String urlPath,Object body, BaseSubscriber responseCallback) {
256 |
257 | Novate novate = new Novate.Builder(activity)
258 | .baseUrl(baseUrl)
259 | .addCookie(false) //是否同步cooike 默认不同步
260 | .addCache(false) //是否缓存 默认缓存
261 | .addLog(true)
262 | .connectTimeout(500000)
263 | .writeTimeout(500000)
264 | .build();
265 | novate.body(urlPath,body,responseCallback);
266 | }
267 |
268 | public static void requestByJson(final Activity activity,final String baseUrl, final String urlPath,String jsonString, BaseSubscriber responseCallback) {
269 |
270 | Novate novate = new Novate.Builder(activity)
271 | .baseUrl(baseUrl)
272 | .addCookie(false) //是否同步cooike 默认不同步
273 | .addCache(false) //是否缓存 默认缓存
274 | .addLog(true)
275 | .connectTimeout(500000)
276 | .writeTimeout(500000)
277 | .build();
278 | novate.json(urlPath,jsonString,responseCallback);
279 | }
280 |
281 | public static void requestByForm(final Activity activity,final String baseUrl, final String urlPath,Map data, BaseSubscriber responseCallback) {
282 |
283 | Novate novate = new Novate.Builder(activity)
284 | .baseUrl(baseUrl)
285 | .addCookie(false) //是否同步cooike 默认不同步
286 | .addCache(false) //是否缓存 默认缓存
287 | .addLog(true)
288 | .connectTimeout(500000)
289 | .writeTimeout(500000)
290 | .build();
291 | novate.form(urlPath,data,responseCallback);
292 | }
293 |
294 |
295 |
296 | public static void requestByObserver(Observer observer, Observable.OnSubscribe stringOnSubscribe ){
297 | //使用Observable.create()创建被观察者
298 | Observable observable1 = Observable.create(stringOnSubscribe);
299 | //订阅
300 | observable1.subscribe(observer);
301 | }
302 | }
303 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/rxjava/RxJavaByUploadDownload.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.rxjava;
2 |
3 | import android.app.Activity;
4 | import android.support.annotation.NonNull;
5 |
6 | import com.tamic.novate.BaseSubscriber;
7 | import com.tamic.novate.Novate;
8 | import com.tamic.novate.callback.RxFileCallBack;
9 | import com.tamic.novate.callback.RxStringCallback;
10 | import com.tamic.novate.download.DownLoadCallBack;
11 | import com.tamic.novate.request.NovateRequestBody;
12 |
13 | import java.io.File;
14 | import java.util.List;
15 | import java.util.Map;
16 |
17 | import okhttp3.MediaType;
18 | import okhttp3.MultipartBody;
19 | import okhttp3.RequestBody;
20 | import okhttp3.ResponseBody;
21 |
22 | public class RxJavaByUploadDownload {
23 |
24 |
25 | public static final String MULTIPART_FORM_DATA = "multipart/form-data";
26 |
27 | @NonNull
28 | private static RequestBody createPartFromString(String descriptionString) {
29 | return RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), descriptionString);
30 | }
31 |
32 | @NonNull
33 | private static MultipartBody.Part prepareFilePart(String partName, String fileName) {
34 | File file =new File(fileName);
35 | // 为file建立RequestBody实例
36 | RequestBody requestFile = RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), file);
37 | // MultipartBody.Part借助文件名完成最终的上传
38 | return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
39 | }
40 |
41 | public static void uploadByImage(Activity activity, String baseUrl, String pathUrl, RequestBody requestFile , BaseSubscriber responseCallback){
42 |
43 | Novate novate = new Novate.Builder(activity)
44 | .baseUrl(baseUrl)
45 | .addCookie(false) //是否同步cooike 默认不同步
46 | .addCache(false) //是否缓存 默认缓存
47 | .addLog(true)
48 | .connectTimeout(500000)
49 | .writeTimeout(500000)
50 | .build();
51 | novate.upload(pathUrl, requestFile, responseCallback );
52 | }
53 |
54 | public static void uploadByImage(Activity activity,String baseUrl,String pathUrl,String filePath, BaseSubscriber responseCallback){
55 | Novate novate = new Novate.Builder(activity)
56 | .baseUrl(baseUrl)
57 | .addCookie(false) //是否同步cooike 默认不同步
58 | .addCache(false) //是否缓存 默认缓存
59 | .addLog(true)
60 | .connectTimeout(500000)
61 | .writeTimeout(500000)
62 | .build();
63 | File file = new File(filePath);
64 | novate.uploadImage(pathUrl, file, responseCallback );
65 |
66 | }
67 |
68 | public static void uploadBySingleFile(Activity activity, String baseUrl,String pathUrl,RequestBody requestFile , BaseSubscriber responseCallback){
69 |
70 | Novate novate = new Novate.Builder(activity)
71 | .baseUrl(baseUrl)
72 | .addCookie(false) //是否同步cooike 默认不同步
73 | .addCache(false) //是否缓存 默认缓存
74 | .addLog(true)
75 | .connectTimeout(500000)
76 | .writeTimeout(500000)
77 | .build();
78 | novate.uploadFlie(pathUrl, requestFile, responseCallback );
79 | }
80 |
81 | public static void uploadByMutipleFile(Activity activity, String baseUrl, String pathUrl, Map mapFiles , BaseSubscriber responseCallback){
82 |
83 | Novate novate = new Novate.Builder(activity)
84 | .baseUrl(baseUrl)
85 | .addCookie(false) //是否同步cooike 默认不同步
86 | .addCache(false) //是否缓存 默认缓存
87 | .addLog(true)
88 | .connectTimeout(500000)
89 | .writeTimeout(500000)
90 | .build();
91 | novate.uploadFlies(pathUrl, mapFiles, responseCallback );
92 | }
93 |
94 | public static void uploadByBodyTextFile(Activity activity, String baseUrl,String pathUrl, RequestBody requestBody , BaseSubscriber responseCallback){
95 |
96 | /* RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
97 | .addFormDataPart("name", "tamic")
98 | .addFormDataPart("pawww.edu800.cnssword", "12345")
99 | .addFormDataPart("atavr", file.getName(), Utils.createImage(mfile))
100 | .build();*/
101 | Novate novate = new Novate.Builder(activity)
102 | .baseUrl(baseUrl)
103 | .addCookie(false) //是否同步cooike 默认不同步
104 | .addCache(false) //是否缓存 默认缓存
105 | .addLog(true)
106 | .connectTimeout(500000)
107 | .writeTimeout(500000)
108 | .build();
109 | novate.upload(pathUrl, requestBody, responseCallback );
110 | }
111 |
112 | public static void uploadByPartTextFile(Activity activity, String baseUrl,String pathUrl,String fileName,String pathName,String descriptions, BaseSubscriber responseCallback){
113 |
114 | /* MultipartBody.Part body = Utils.createPart("key", file);
115 | String descriptionString = "文件描述";
116 | RequestBody description = Utils.createPartFromString(descriptionString);*/
117 | Novate novate = new Novate.Builder(activity)
118 | .baseUrl(baseUrl)
119 | .addCookie(false) //是否同步cooike 默认不同步
120 | .addCache(false) //是否缓存 默认缓存
121 | .addLog(true)
122 | .connectTimeout(500000)
123 | .writeTimeout(500000)
124 | .build();
125 | MultipartBody.Part body = prepareFilePart(fileName, pathName);
126 | RequestBody descriptionString = createPartFromString(descriptions);
127 | // 执行
128 | novate.uploadFlie(pathUrl,descriptionString,body,responseCallback);
129 | }
130 |
131 | public static void downloadBigFile(Activity activity,String baseUrl,String pathUrl,DownLoadCallBack downLoadCallBack){
132 | Novate novate = new Novate.Builder(activity)
133 | .baseUrl(baseUrl)
134 | .addCookie(false) //是否同步cooike 默认不同步
135 | .addCache(false) //是否缓存 默认缓存
136 | .addLog(true)
137 | .connectTimeout(500000)
138 | .writeTimeout(500000)
139 | .build();
140 | novate.download(pathUrl,downLoadCallBack);
141 | }
142 |
143 | public static void downloadBigFileAndName(Activity activity,String baseUrl,String pathUrl,String fileName,DownLoadCallBack downLoadCallBack){
144 | Novate novate = new Novate.Builder(activity)
145 | .baseUrl(baseUrl)
146 | .addCookie(false) //是否同步cooike 默认不同步
147 | .addCache(false) //是否缓存 默认缓存
148 | .addLog(true)
149 | .connectTimeout(500000)
150 | .writeTimeout(500000)
151 | .build();
152 | novate.download(pathUrl,fileName,downLoadCallBack);
153 | }
154 |
155 | public static void downloadBigFileAndPath(Activity activity,String baseUrl,String pathUrl,String key,String savePath,String fileName,DownLoadCallBack downLoadCallBack){
156 | Novate novate = new Novate.Builder(activity)
157 | .baseUrl(baseUrl)
158 | .addCookie(false) //是否同步cooike 默认不同步
159 | .addCache(false) //是否缓存 默认缓存
160 | .addLog(true)
161 | .connectTimeout(500000)
162 | .writeTimeout(500000)
163 | .build();
164 | novate.download(key,pathUrl,savePath,fileName,downLoadCallBack);
165 | }
166 |
167 | public static void downloadMinFile(Activity activity,String baseUrl,String pathUrl,DownLoadCallBack downLoadCallBack){
168 | Novate novate = new Novate.Builder(activity)
169 | .baseUrl(baseUrl)
170 | .addCookie(false) //是否同步cooike 默认不同步
171 | .addCache(false) //是否缓存 默认缓存
172 | .addLog(true)
173 | .connectTimeout(500000)
174 | .writeTimeout(500000)
175 | .build();
176 | novate.downloadMin(pathUrl,downLoadCallBack);
177 | }
178 |
179 |
180 | public static void downloadMinFileAndName(Activity activity,String baseUrl,String pathUrl,String fileName,DownLoadCallBack downLoadCallBack){
181 | Novate novate = new Novate.Builder(activity)
182 | .baseUrl(baseUrl)
183 | .addCookie(false) //是否同步cooike 默认不同步
184 | .addCache(false) //是否缓存 默认缓存
185 | .addLog(true)
186 | .connectTimeout(500000)
187 | .writeTimeout(500000)
188 | .build();
189 | novate.downloadMin(pathUrl,fileName,downLoadCallBack);
190 | }
191 |
192 | public static void downloadMinFileAndPath(Activity activity,String baseUrl,String pathUrl,String key,String savePath,String fileName,DownLoadCallBack downLoadCallBack){
193 | Novate novate = new Novate.Builder(activity)
194 | .baseUrl(baseUrl)
195 | .addCookie(false) //是否同步cooike 默认不同步
196 | .addCache(false) //是否缓存 默认缓存
197 | .addLog(true)
198 | .connectTimeout(500000)
199 | .writeTimeout(500000)
200 | .build();
201 | novate.downloadMin(key,pathUrl,savePath,fileName,downLoadCallBack);
202 | }
203 |
204 |
205 |
206 | public static void uploadByRxUploadWithPartAndKey(Activity activity, String baseUrl,String description, NovateRequestBody requestBody , String pathUrl, String filePath,String fileName, BaseSubscriber responseCallback){
207 |
208 | /* RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data; charset=utf-8"), file);
209 | final NovateRequestBody requestBody = Utils.createNovateRequestBody(requestFile, new UpLoadCallback() {
210 |
211 | @Override
212 | public void onProgress(Object tag, int progress, long speed, boolean done) {
213 |
214 | updateProgressDialog(progress);
215 | }
216 | });*/
217 |
218 | Novate novate = new Novate.Builder(activity)
219 | .baseUrl(baseUrl)
220 | .addCookie(false) //是否同步cooike 默认不同步
221 | .addCache(false) //是否缓存 默认缓存
222 | .addLog(true)
223 | .connectTimeout(500000)
224 | .writeTimeout(500000)
225 | .build();
226 | File file = new File(filePath);
227 |
228 | MultipartBody.Part body = MultipartBody.Part.createFormData(fileName, file.getName(), requestBody);
229 | RequestBody descriptionString = createPartFromString(description);
230 | novate.uploadFlie(pathUrl,descriptionString, body, responseCallback);
231 |
232 |
233 | }
234 |
235 |
236 |
237 | public static void downloadByRxGet(Activity activity,String pathUrl,Map parameters,RxFileCallBack rxFileCallBack){
238 | Novate novate = new Novate.Builder(activity)
239 | .addCookie(false) //是否同步cooike 默认不同步
240 | .addCache(false) //是否缓存 默认缓存
241 | .addLog(true)
242 | .connectTimeout(500000)
243 | .writeTimeout(500000)
244 | .build();
245 | novate.rxGet(pathUrl, parameters, rxFileCallBack);
246 |
247 | }
248 | }
249 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/ActivityCollector.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 | import android.app.Activity;
4 |
5 | import java.util.LinkedList;
6 |
7 | /**
8 | * File description.
9 | *
10 | * @author Frank
11 | * @date 2018/2/5
12 | * @emial 1320259466@qq.com
13 | * @description (about file's use)
14 | */
15 |
16 | public class ActivityCollector {
17 |
18 | public static LinkedList activities = new LinkedList();
19 |
20 | public static void addActivity(Activity activity) {
21 | activities.add(activity);
22 | }
23 |
24 | public static void removeActivity(Activity activity) {
25 | activities.remove(activity);
26 | }
27 |
28 | public static void finishAll() {
29 | for (Activity activity : activities) {
30 | if (!activity.isFinishing()) {
31 | activity.finish();
32 | }
33 | }
34 | }
35 |
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/Apires.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 | import com.alibaba.fastjson.JSON;
4 | import com.alibaba.fastjson.serializer.SerializerFeature;
5 |
6 | public class Apires {
7 | public int status;
8 | public String message;
9 | public Object data;
10 |
11 | public Apires(){
12 | this.status = 0;
13 | this.message = "";
14 | this.data = new Object();
15 | }
16 | public Apires message(String m ){
17 | this.message = m;
18 | return this;
19 | }
20 | public Apires data(Object data ){
21 | this.data = data;
22 | return this;
23 | }
24 | public String fail(){
25 | this.status = 1;
26 | return Apires.toJSON(this);
27 | }
28 | public String fail(String msg){
29 | this.message(msg);
30 | this.status = 1;
31 | return Apires.toJSON(this);
32 | }
33 | public String success(){
34 | this.status = 0;
35 | return Apires.toJSON(this);
36 | }
37 |
38 | public static String toJSON(Apires as){
39 | return JSON.toJSONString(as, SerializerFeature.WriteMapNullValue);
40 | }
41 | }
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/AppManager.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 | import android.app.Activity;
4 | import android.app.ActivityManager;
5 | import android.content.Context;
6 |
7 | import java.util.LinkedList;
8 |
9 | /**
10 | * 应用程序Activity管理类:用于Activity管理和应用程序退出
11 | */
12 | public class AppManager {
13 |
14 | private static LinkedList activityStack;
15 | private static AppManager instance;
16 |
17 | private AppManager() {
18 | }
19 |
20 | /**
21 | * 单一实例
22 | */
23 | public static AppManager getAppManager() {
24 | if (instance == null) {
25 | instance = new AppManager();
26 | }
27 | return instance;
28 | }
29 |
30 | /**
31 | * 添加Activity到堆栈
32 | */
33 | public void addActivity(Activity activity) {
34 | if (activityStack == null) {
35 | activityStack = new LinkedList();
36 | }
37 | activityStack.add(activity);
38 | }
39 |
40 | /**
41 | * 获取当前Activity(堆栈中最后一个压入的)
42 | */
43 | public Activity currentActivity() {
44 | Activity activity = activityStack.getLast();
45 | return activity;
46 | }
47 |
48 | /**
49 | * 结束当前Activity(堆栈中最后一个压入的)
50 | */
51 | public void finishActivity() {
52 | Activity activity = activityStack.getLast();
53 | finishActivity(activity);
54 | }
55 |
56 | /**
57 | * 结束指定的Activity
58 | */
59 | public void finishActivity(Activity activity) {
60 | if (activity != null) {
61 | if (activityStack != null) {
62 | activityStack.remove(activity);
63 | }
64 | activity.finish();
65 | activity = null;
66 | }
67 | }
68 |
69 | /**
70 | * 结束指定类名的Activity
71 | */
72 | public void finishActivity(Class> cls) {
73 | for (Activity activity : activityStack) {
74 | if (activity.getClass().equals(cls)) {
75 | finishActivity(activity);
76 | }
77 | }
78 | }
79 |
80 | /**
81 | * 结束所有Activity
82 | */
83 | public void finishAllActivity() {
84 | for (int i = 0, size = activityStack.size(); i < size; i++) {
85 | if (null != activityStack.get(i)) {
86 | activityStack.get(i).finish();
87 | }
88 | }
89 | activityStack.clear();
90 | //System.exit(0);
91 | }
92 |
93 | /**
94 | * 退出应用程序
95 | */
96 | public void AppExit(Context context) {
97 | try {
98 | finishAllActivity();
99 | ActivityManager activityMgr = (ActivityManager) context
100 | .getSystemService(Context.ACTIVITY_SERVICE);
101 | activityMgr.restartPackage(context.getPackageName());
102 | System.exit(0);
103 | } catch (Exception e) {
104 | }
105 | }
106 |
107 | public int ActivityStackSize() {
108 | return activityStack == null ? 0 : activityStack.size();
109 | }
110 | }
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/ClickUtils.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 | public class ClickUtils {
4 | private static final int MIN_DELAY_TIME= 2000; // 两次点击间隔不能少于2000ms
5 | private static long lastClickTime;
6 |
7 | public static boolean isFastClick() {
8 | boolean flag = true;
9 | long currentClickTime = System.currentTimeMillis();
10 | if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
11 | flag = false;
12 | }
13 | lastClickTime = currentClickTime;
14 | return flag;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/DESUtils.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 | import java.io.ByteArrayOutputStream;
4 | import java.io.IOException;
5 | import java.io.OutputStream;
6 | import java.io.UnsupportedEncodingException;
7 | import java.security.Key;
8 |
9 | import javax.crypto.Cipher;
10 | import javax.crypto.SecretKeyFactory;
11 | import javax.crypto.spec.DESedeKeySpec;
12 | import javax.crypto.spec.IvParameterSpec;
13 |
14 | public class DESUtils {
15 |
16 | // 密钥
17 | private final static String secretKey = "com.construct.platform?#@" ;
18 | // 向量
19 | private final static String iv = "01234567" ;
20 | // 加解密统一使用的编码方式
21 | private final static String encoding = "utf-8" ;
22 |
23 | /**
24 | * 3DES加密
25 | *
26 | * @param plainText 普通文本
27 | * @return
28 | * @throws Exception
29 | */
30 | public static String encode(String plainText) throws Exception {
31 | Key deskey = null ;
32 | DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
33 | SecretKeyFactory keyfactory = SecretKeyFactory.getInstance( "desede" );
34 | deskey = keyfactory.generateSecret(spec);
35 |
36 | Cipher cipher = Cipher.getInstance( "desede/CBC/PKCS5Padding" );
37 | IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
38 | cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
39 | byte [] encryptData = cipher.doFinal(plainText.getBytes(encoding));
40 | return Base64.encode(encryptData);
41 | }
42 |
43 | /**
44 | * 3DES解密
45 | *
46 | * @param encryptText 加密文本
47 | * @return
48 | * @throws Exception
49 | */
50 | public static String decode(String encryptText) throws Exception {
51 | Key deskey = null ;
52 | DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
53 | SecretKeyFactory keyfactory = SecretKeyFactory.getInstance( "desede" );
54 | deskey = keyfactory.generateSecret(spec);
55 | Cipher cipher = Cipher.getInstance( "desede/CBC/PKCS5Padding" );
56 | IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
57 | cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
58 |
59 | byte [] decryptData = cipher.doFinal(Base64.decode(encryptText));
60 |
61 | return new String(decryptData, encoding);
62 | }
63 |
64 | public static String padding(String str) {
65 | byte[] oldByteArray;
66 | try {
67 | oldByteArray = str.getBytes("UTF8");
68 | int numberToPad = 8 - oldByteArray.length % 8;
69 | byte[] newByteArray = new byte[oldByteArray.length + numberToPad];
70 | System.arraycopy(oldByteArray, 0, newByteArray, 0,
71 | oldByteArray.length);
72 | for (int i = oldByteArray.length; i < newByteArray.length; ++i) {
73 | newByteArray[i] = 0;
74 | }
75 | return new String(newByteArray, "UTF8");
76 | } catch (UnsupportedEncodingException e) {
77 | System.out.println("Crypter.padding UnsupportedEncodingException");
78 | }
79 | return null;
80 | }
81 |
82 | /**
83 | * Base64编码工具类
84 | *
85 | */
86 | public static class Base64 {
87 | private static final char [] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .toCharArray();
88 |
89 | public static String encode( byte [] data) {
90 | int start = 0 ;
91 | int len = data.length;
92 | StringBuffer buf = new StringBuffer(data.length * 3 / 2 );
93 |
94 | int end = len - 3 ;
95 | int i = start;
96 | int n = 0 ;
97 |
98 | while (i <= end) {
99 | int d = (((( int ) data[i]) & 0x0ff ) << 16 ) | (((( int ) data[i + 1 ]) & 0x0ff ) << 8 ) | ((( int ) data[i + 2 ]) & 0x0ff );
100 |
101 | buf.append(legalChars[(d >> 18 ) & 63 ]);
102 | buf.append(legalChars[(d >> 12 ) & 63 ]);
103 | buf.append(legalChars[(d >> 6 ) & 63 ]);
104 | buf.append(legalChars[d & 63 ]);
105 |
106 | i += 3 ;
107 |
108 | if (n++ >= 14 ) {
109 | n = 0 ;
110 | buf.append( " " );
111 | }
112 | }
113 |
114 | if (i == start + len - 2 ) {
115 | int d = (((( int ) data[i]) & 0x0ff ) << 16 ) | (((( int ) data[i + 1 ]) & 255 ) << 8 );
116 |
117 | buf.append(legalChars[(d >> 18 ) & 63 ]);
118 | buf.append(legalChars[(d >> 12 ) & 63 ]);
119 | buf.append(legalChars[(d >> 6 ) & 63 ]);
120 | buf.append( "=" );
121 | } else if (i == start + len - 1 ) {
122 | int d = ((( int ) data[i]) & 0x0ff ) << 16 ;
123 |
124 | buf.append(legalChars[(d >> 18 ) & 63 ]);
125 | buf.append(legalChars[(d >> 12 ) & 63 ]);
126 | buf.append( "==" );
127 | }
128 |
129 | return buf.toString();
130 | }
131 |
132 | private static int decode( char c) {
133 | if (c >= 'A' && c <= 'Z' )
134 | return (( int ) c) - 65 ;
135 | else if (c >= 'a' && c <= 'z' )
136 | return (( int ) c) - 97 + 26 ;
137 | else if (c >= '0' && c <= '9' )
138 | return (( int ) c) - 48 + 26 + 26 ;
139 | else
140 | switch (c) {
141 | case '+' :
142 | return 62 ;
143 | case '/' :
144 | return 63 ;
145 | case '=' :
146 | return 0 ;
147 | default :
148 | throw new RuntimeException( "unexpected code: " + c);
149 | }
150 | }
151 |
152 | /**
153 | * Decodes the given Base64 encoded String to a new byte array. The byte array holding the decoded data is returned.
154 | */
155 |
156 | public static byte [] decode(String s) {
157 |
158 | ByteArrayOutputStream bos = new ByteArrayOutputStream();
159 | try {
160 | decode(s, bos);
161 | } catch (IOException e) {
162 | throw new RuntimeException();
163 | }
164 | byte [] decodedBytes = bos.toByteArray();
165 | try {
166 | bos.close();
167 | bos = null ;
168 | } catch (IOException ex) {
169 | System.err.println( "Error while decoding BASE64: " + ex.toString());
170 | }
171 | return decodedBytes;
172 | }
173 |
174 | private static void decode(String s, OutputStream os) throws IOException {
175 | int i = 0 ;
176 |
177 | int len = s.length();
178 |
179 | while ( true ) {
180 | while (i < len && s.charAt(i) <= ' ' )
181 | i++;
182 |
183 | if (i == len)
184 | break ;
185 |
186 | int tri = (decode(s.charAt(i)) << 18 ) + (decode(s.charAt(i + 1 )) << 12 ) + (decode(s.charAt(i + 2 )) << 6 ) + (decode(s.charAt(i + 3 )));
187 |
188 | os.write((tri >> 16 ) & 255 );
189 | if (s.charAt(i + 2 ) == '=' )
190 | break ;
191 | os.write((tri >> 8 ) & 255 );
192 | if (s.charAt(i + 3 ) == '=' )
193 | break ;
194 | os.write(tri & 255 );
195 |
196 | i += 4 ;
197 | }
198 | }
199 | }
200 |
201 | // public static void doDES throws Exception{
202 | // String plainText = "来自http://my.oschina.net/penngo的博客";
203 | // String encryptText = DES3.encode(plainText);
204 | // System.out.println(encryptText);
205 | // System.out.println(DES3.decode(encryptText));
206 | //
207 | //
208 | // }
209 |
210 | }
211 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/DeleteFile.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 | import java.io.File;
4 |
5 | /**
6 | * Created by Frank on 2017/12/7.
7 | */
8 |
9 | public class DeleteFile {
10 | public static boolean deleteFile(String filePath){
11 |
12 | try{
13 | File file = new File(filePath);
14 | if(file.exists()){
15 | file.delete();
16 | }
17 | }catch (Exception ex){
18 | ex.printStackTrace();
19 | return false;
20 | }
21 | return true;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/ExitAPP.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 | import android.app.ActivityManager;
4 | import android.content.Context;
5 |
6 | /**
7 | * File description.
8 | *
9 | * @author Frank
10 | * @date 2018/2/5
11 | * @emial 1320259466@qq.com
12 | * @description (about file's use)
13 | */
14 |
15 | public class ExitAPP {
16 | public static void AppExit(Context context) {
17 | try {
18 | //ActivityCollector.finishAll();
19 | ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
20 | activityMgr.killBackgroundProcesses(context.getPackageName());
21 | System.exit(0);
22 | } catch (Exception ignored) {
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/GsonRequest.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 | import com.android.volley.NetworkResponse;
4 | import com.android.volley.ParseError;
5 | import com.android.volley.Request;
6 | import com.android.volley.Response;
7 | import com.android.volley.toolbox.HttpHeaderParser;
8 | import com.google.gson.Gson;
9 |
10 | import java.io.UnsupportedEncodingException;
11 |
12 | public class GsonRequest extends Request {
13 | private final Response.Listener mListener;
14 | private Gson mGson;
15 | private Class mClass;
16 | public GsonRequest(int method, String url, Class clazz, Response.Listener listener, Response.ErrorListener errorListener) {
17 | super(method, url, errorListener);
18 | mGson = new Gson();
19 | mClass = clazz;
20 | mListener = listener;
21 | }
22 |
23 | public GsonRequest(String url, Class clazz, Response.Listener listener, Response.ErrorListener errorListener) {
24 | this(Method.GET, url, clazz, listener, errorListener);
25 | }
26 |
27 | @Override
28 | protected Response parseNetworkResponse(NetworkResponse response) {
29 | try {
30 | String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
31 | //结合Gson解析
32 | return Response.success(mGson.fromJson(jsonString, mClass), HttpHeaderParser.parseCacheHeaders(response));
33 | } catch (UnsupportedEncodingException e) {
34 | return Response.error(new ParseError(e));
35 | }
36 | }
37 |
38 | @Override
39 | protected void deliverResponse(T response) {
40 | mListener.onResponse(response);
41 | }
42 | }
43 |
44 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/JsonTimeUtil.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 |
4 | import com.alibaba.fastjson.JSON;
5 | import com.alibaba.fastjson.serializer.SerializeConfig;
6 | import com.alibaba.fastjson.serializer.SerializerFeature;
7 | import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
8 |
9 | import java.util.Date;
10 |
11 | /**
12 | * Created by 黄庆 on 2017/12/31.
13 | */
14 |
15 | //将 jsonObject 转换成 对象
16 |
17 | public class JsonTimeUtil {
18 | private static SerializeConfig mapping = new SerializeConfig();
19 | private static String[] dateFormat={"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd","yyyy-MM-dd HH:mm"};
20 | /**
21 | * 默认的处理时间
22 | *
23 | * @param jsonText
24 | * @return
25 | */
26 | public static String toJSON(Object jsonText) {
27 | return JSON.toJSONString(jsonText,
28 | SerializerFeature.WriteDateUseDateFormat);
29 | }
30 |
31 | /**
32 | * 自定义时间格式
33 | *
34 | * @param jsonText
35 | * @return
36 | */
37 | public static String toDatetimeJSONString(Object jsonText) {
38 | mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat[0]));
39 | return JSON.toJSONString(jsonText, mapping).replaceAll("\"","");
40 | }
41 | public static String toDateMinJSONString(Object jsonText) {
42 | mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat[2]));
43 | return JSON.toJSONString(jsonText, mapping).replaceAll("\"","");
44 | }
45 | public static String toDateJSONString(Object jsonText) {
46 | mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat[1]));
47 | return JSON.toJSONString(jsonText, mapping).replaceAll("\"","");
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/Kish.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 | import java.util.ArrayList;
4 |
5 | public class Kish {
6 |
7 | public static int getMember( int number, String kishRule){
8 | int m = 0;
9 | switch (kishRule){
10 | case "A":m = 1;
11 | break;
12 | case "B1":{
13 | switch (number){
14 | case 1: case 2: case 3: case 4:m = 1;break;
15 | case 5: case 6: default:m = 2;break;
16 | }
17 | }
18 | break;
19 | case "B2":
20 | switch (number){
21 | case 1: case 2: case 3: m = 1;break;
22 | case 4: case 5: case 6: default:m = 2;break;
23 | }
24 | break;
25 | case "C":
26 | switch (number){
27 | case 1: case 2: m = 1;break;
28 | case 3: case 4: m = 2;break;
29 | case 5: case 6: default:m = 3;break;
30 | }
31 | break;
32 | case "D":
33 | switch (number){
34 | case 1: m = 1;break;
35 | case 2: case 3: m = 2;break;
36 | case 4: m = 3;break;
37 | case 5: case 6: default:m = 4;break;
38 | }
39 | break;
40 | case "E1":
41 | switch (number){
42 | case 1: m = 1;break;
43 | case 2: m = 2;break;
44 | case 3: case 4: case 5: m = 3;break;
45 | case 6: default:m = 5;break;
46 | }
47 | break;
48 | case "E2":
49 | switch (number){
50 | case 1: m = 1;break;
51 | case 2: case 3: m = 2;break;
52 | case 4: m = 4;break;
53 | case 5: case 6: default:m = 5;break;
54 | }
55 | break;
56 | case "F":
57 | switch (number){
58 | case 1: m = 1;break;
59 | case 2: m = 2;break;
60 | case 3: m = 3;break;
61 | case 4: m = 4;break;
62 | case 5: m = 5;break;
63 | case 6: default:m = 6;break;
64 | }
65 | break;
66 | default:break;
67 | }
68 | return m;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/L.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 | import android.util.Log;
4 |
5 | /**
6 | * PROJECT_NAME:SZJDSpecialDeviceExam
7 | * PACKAGE_NAME:com.example.frank.jinding.Log
8 | * USER:Frank
9 | * DATE:2018/6/19
10 | * TIME:4:25
11 | * DAY_NAME_FULL:星期日
12 | * DESCRIPTION:On the description and function of the document
13 | **/
14 | public class L {
15 |
16 | public static final String TAG="Log Info : ";
17 | public static boolean debug=true;
18 |
19 | public static void g(String msg){
20 | if (debug){
21 | Log.e(TAG,msg);
22 | }
23 | }
24 |
25 |
26 | public static void g(String tag,String msg){
27 | if (debug){
28 | Log.e(TAG,tag+":=:"+msg);
29 | }
30 | }
31 |
32 | public static void a(Object[] msg){
33 | if (debug){
34 | for (Object obj:msg) {
35 | Log.e(TAG,""+obj.toString());
36 | }
37 |
38 | }
39 | }
40 |
41 |
42 | public static void a(String tag,Object[] msg){
43 | if (debug){
44 | for (Object obj:msg) {
45 | Log.e(TAG,tag+":=:"+obj.toString());
46 | }
47 |
48 | }
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/MakeSSLSocketFactory.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 | import java.io.ByteArrayInputStream;
4 | import java.io.IOException;
5 | import java.io.InputStream;
6 | import java.security.KeyManagementException;
7 | import java.security.KeyStore;
8 | import java.security.KeyStoreException;
9 | import java.security.NoSuchAlgorithmException;
10 | import java.security.cert.Certificate;
11 | import java.security.cert.CertificateException;
12 | import java.security.cert.CertificateFactory;
13 |
14 | import javax.net.ssl.SSLContext;
15 | import javax.net.ssl.SSLSocketFactory;
16 | import javax.net.ssl.TrustManagerFactory;
17 |
18 | public class MakeSSLSocketFactory {
19 | private final String RFC ="XXX...";
20 |
21 | /**
22 | * 生成SSLSocketFactory
23 | *@return
24 | */
25 | private SSLSocketFactory initSSLSocketFactory() {
26 | //生成证书:Certificate
27 | CertificateFactory cf = null;
28 | SSLSocketFactory factory = null;
29 | try {
30 | cf = CertificateFactory.getInstance("X.509");
31 | InputStream caInput = new ByteArrayInputStream(RFC.getBytes()); // 通过证书生成的RFC格式数据字符串
32 | //InputStream caInput = new BufferedInputStream(newFileInputStream("xxx.crt")); // 证书文件
33 |
34 | Certificate ca = null;
35 | try {
36 | ca = cf.generateCertificate(caInput);
37 | } finally {
38 | try {
39 | caInput.close();
40 | } catch (IOException e) {
41 | e.printStackTrace();
42 | }
43 | }
44 |
45 | //初始化公钥:keyStore
46 | String keyType = KeyStore.getDefaultType();
47 | KeyStore keyStore = KeyStore.getInstance(keyType);
48 | keyStore.load(null, null);
49 | keyStore.setCertificateEntry("ca", ca);
50 |
51 | //初始化TrustManagerFactory
52 | String algorithm = TrustManagerFactory.getDefaultAlgorithm();
53 | TrustManagerFactory managerFactory =TrustManagerFactory.getInstance(algorithm);
54 | managerFactory.init(keyStore);
55 |
56 | //初始化sslContext
57 | SSLContext sslContext = SSLContext.getInstance("TLS");
58 | sslContext.init(null, managerFactory.getTrustManagers(), null);
59 | factory = sslContext.getSocketFactory();
60 |
61 | }catch (CertificateException e) {
62 | e.printStackTrace();
63 | }catch (NoSuchAlgorithmException e) {
64 | e.printStackTrace();
65 | }catch (KeyStoreException e) {
66 | e.printStackTrace();
67 | }catch (IOException e) {
68 | e.printStackTrace();
69 | }catch (KeyManagementException e) {
70 | e.printStackTrace();
71 | }
72 | return factory;
73 | }
74 |
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/Md5Tool.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 | import java.security.MessageDigest;
4 | import java.security.NoSuchAlgorithmException;
5 |
6 |
7 | public class Md5Tool {
8 |
9 | private static String bytesToHexString(byte[] bytes) {
10 | StringBuilder sb = new StringBuilder();
11 | for (int i = 0; i < bytes.length; i++) {
12 | String hex = Integer.toHexString(0xFF & bytes[i]);
13 | if (hex.length() == 1) {
14 | sb.append('0');
15 | }
16 | sb.append(hex);
17 | }
18 | return sb.toString();
19 | }
20 |
21 | public static String hashKey(String key) {
22 | String hashKey;
23 | try {
24 | final MessageDigest mDigest = MessageDigest.getInstance("MD5");
25 | mDigest.update(key.getBytes());
26 | hashKey = bytesToHexString(mDigest.digest());
27 | } catch (NoSuchAlgorithmException e) {
28 | hashKey = String.valueOf(key.hashCode());
29 | }
30 | return hashKey;
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/Md5util.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 | import org.apache.commons.net.util.Base64;
4 | import java.io.UnsupportedEncodingException;
5 | import java.security.MessageDigest;
6 | import java.security.NoSuchAlgorithmException;
7 |
8 | public class Md5util {
9 | public static String md5(String password) throws UnsupportedEncodingException
10 | {
11 | MessageDigest md;
12 | try {
13 | md = MessageDigest.getInstance("md5");
14 | byte md5[]=md.digest(password.getBytes("utf-8"));
15 | return new String(Base64.encodeBase64(md5)); //使用apache工具包里的Base64进行加密
16 | } catch (NoSuchAlgorithmException e) {
17 | // TODO Auto-generated catch block
18 | throw new RuntimeException(e);
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/OpenFile.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 | import android.content.ActivityNotFoundException;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.net.Uri;
7 | import android.widget.Toast;
8 |
9 | import java.io.File;
10 |
11 | /**
12 | * PROJECT_NAME:SZJDSpecialDeviceExam
13 | * PACKAGE_NAME:com.example.frank.jinding.Utils
14 | * USER:Frank
15 | * DATE:2018/6/3
16 | * TIME:20:03
17 | * DAY_NAME_FULL:星期日
18 | * DESCRIPTION:On the description and function of the document
19 | **/
20 | public class OpenFile {
21 |
22 | private static String[][] MIME_MapTable={
23 | //{后缀名,MIME类型}
24 | {".3gp", "video/3gpp"},
25 | {".apk", "application/vnd.android.package-archive"},
26 | {".asf", "video/x-ms-asf"},
27 | {".avi", "video/x-msvideo"},
28 | {".bin", "application/octet-stream"},
29 | {".bmp", "image/bmp"},
30 | {".c", "text/plain"},
31 | {".class", "application/octet-stream"},
32 | {".conf", "text/plain"},
33 | {".cpp", "text/plain"},
34 | {".doc", "application/msword"},
35 | {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
36 | {".xls", "application/vnd.ms-excel"},
37 | {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
38 | {".exe", "application/octet-stream"},
39 | {".gif", "image/gif"},
40 | {".gtar", "application/x-gtar"},
41 | {".gz", "application/x-gzip"},
42 | {".h", "text/plain"},
43 | {".htm", "text/html"},
44 | {".html", "text/html"},
45 | {".jar", "application/java-archive"},
46 | {".java", "text/plain"},
47 | {".jpeg", "image/jpeg"},
48 | {".jpg", "image/jpeg"},
49 | {".js", "application/x-javascript"},
50 | {".log", "text/plain"},
51 | {".m3u", "audio/x-mpegurl"},
52 | {".m4a", "audio/mp4a-latm"},
53 | {".m4b", "audio/mp4a-latm"},
54 | {".m4p", "audio/mp4a-latm"},
55 | {".m4u", "video/vnd.mpegurl"},
56 | {".m4v", "video/x-m4v"},
57 | {".mov", "video/quicktime"},
58 | {".mp2", "audio/x-mpeg"},
59 | {".mp3", "audio/x-mpeg"},
60 | {".mp4", "video/mp4"},
61 | {".mpc", "application/vnd.mpohun.certificate"},
62 | {".mpe", "video/mpeg"},
63 | {".mpeg", "video/mpeg"},
64 | {".mpg", "video/mpeg"},
65 | {".mpg4", "video/mp4"},
66 | {".mpga", "audio/mpeg"},
67 | {".msg", "application/vnd.ms-outlook"},
68 | {".ogg", "audio/ogg"},
69 | {".pdf", "application/pdf"},
70 | {".png", "image/png"},
71 | {".pps", "application/vnd.ms-powerpoint"},
72 | {".ppt", "application/vnd.ms-powerpoint"},
73 | {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
74 | {".prop", "text/plain"},
75 | {".rc", "text/plain"},
76 | {".rmvb", "audio/x-pn-realaudio"},
77 | {".rtf", "application/rtf"},
78 | {".sh", "text/plain"},
79 | {".tar", "application/x-tar"},
80 | {".tgz", "application/x-compressed"},
81 | {".txt", "text/plain"},
82 | {".wav", "audio/x-wav"},
83 | {".wma", "audio/x-ms-wma"},
84 | {".wmv", "audio/x-ms-wmv"},
85 | {".wps", "application/vnd.ms-works"},
86 | {".xml", "text/plain"},
87 | {".z", "application/x-compress"},
88 | {".zip", "application/x-zip-compressed"},
89 | {"", "*/*"}
90 | };
91 |
92 |
93 | public static void openFile(Context context, File file){
94 | try{
95 | Intent intent = new Intent();
96 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
97 | //设置intent的Action属性
98 | intent.setAction(Intent.ACTION_VIEW);
99 | //获取文件file的MIME类型
100 | String type = getMIMEType(file);
101 | //设置intent的data和Type属性。
102 | intent.setDataAndType(/*uri*/Uri.fromFile(file), type);
103 | //跳转
104 | context.startActivity(intent);
105 | // Intent.createChooser(intent, "请选择对应的软件打开该附件!");
106 | }catch (ActivityNotFoundException e) {
107 | // TODO: handle exception
108 | Toast.makeText(context, "文件不能打开,请下载相关软件!", Toast.LENGTH_SHORT).show();
109 | }
110 | }
111 | private static String getMIMEType(File file) {
112 |
113 | String type="*/*";
114 | String fName = file.getName();
115 | //获取后缀名前的分隔符"."在fName中的位置。
116 | int dotIndex = fName.lastIndexOf(".");
117 | if(dotIndex < 0){
118 | return type;
119 | }
120 | /* 获取文件的后缀名*/
121 | String end=fName.substring(dotIndex,fName.length()).toLowerCase();
122 | if(end=="")return type;
123 | //在MIME和文件类型的匹配表中找到对应的MIME类型。
124 | for(int i=0;i map, Class> beanClass) throws Exception {
22 |
23 | if (map == null || map.size()<=0)
24 |
25 | return null;
26 |
27 |
28 |
29 | Object obj = beanClass.newInstance();
30 |
31 | //获取关联的所有类,本类以及所有父类
32 |
33 | boolean ret = true;
34 |
35 | Class oo = obj.getClass();
36 |
37 | List clazzs = new ArrayList();
38 |
39 | while(ret){
40 |
41 | clazzs.add(oo);
42 |
43 | oo = oo.getSuperclass();
44 |
45 | if(oo == null || oo == Object.class)break;
46 |
47 | }
48 |
49 |
50 |
51 | for(int i=0;i objectToMap(Object obj) throws Exception {
86 |
87 | if(obj == null){
88 |
89 | return null;
90 |
91 | }
92 |
93 | //获取关联的所有类,本类以及所有父类
94 |
95 | boolean ret = true;
96 |
97 | Class oo = obj.getClass();
98 |
99 | List clazzs = new ArrayList();
100 |
101 | while(ret){
102 |
103 | clazzs.add(oo);
104 |
105 | oo = oo.getSuperclass();
106 |
107 | if(oo == null || oo == Object.class)break;
108 |
109 | }
110 |
111 |
112 |
113 | Map map = new HashMap();
114 |
115 |
116 |
117 | for(int i=0;i dateFormater = new ThreadLocal() {
30 | @Override
31 | protected SimpleDateFormat initialValue() {
32 | return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
33 | }
34 | };
35 |
36 | private final static ThreadLocal dateFormater2 = new ThreadLocal() {
37 | @Override
38 | protected SimpleDateFormat initialValue() {
39 | return new SimpleDateFormat("yyyy-MM-dd");
40 | }
41 | };
42 |
43 | /**
44 | * 将字符串转位日期类型
45 | *
46 | * @param sdate
47 | * @return
48 | */
49 | public static Date toDate(String sdate) {
50 | try {
51 | return dateFormater.get().parse(sdate);
52 | } catch (ParseException e) {
53 | return null;
54 | }
55 | }
56 |
57 | /**
58 | * 以友好的方式显示时间
59 | *
60 | * @param sdate
61 | * @return
62 | */
63 | public static String friendlyTime(String sdate) {
64 | Date time = toDate(sdate);
65 | if (time == null) {
66 | return "Unknown";
67 | }
68 | String ftime = "";
69 | Calendar cal = Calendar.getInstance();
70 |
71 | // 判断是否是同一天
72 | String curDate = dateFormater2.get().format(cal.getTime());
73 | String paramDate = dateFormater2.get().format(time);
74 | if (curDate.equals(paramDate)) {
75 | int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
76 | if (hour == 0)
77 | ftime = Math.max(
78 | (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
79 | + "分钟前";
80 | else
81 | ftime = hour + "小时前";
82 | return ftime;
83 | }
84 |
85 | long lt = time.getTime() / 86400000;
86 | long ct = cal.getTimeInMillis() / 86400000;
87 | int days = (int) (ct - lt);
88 | if (days == 0) {
89 | int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
90 | if (hour == 0)
91 | ftime = Math.max(
92 | (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
93 | + "分钟前";
94 | else
95 | ftime = hour + "小时前";
96 | } else if (days == 1) {
97 | ftime = "昨天";
98 | } else if (days == 2) {
99 | ftime = "前天";
100 | } else if (days > 2 && days <= 10) {
101 | ftime = days + "天前";
102 | } else if (days > 10) {
103 | ftime = dateFormater2.get().format(time);
104 | }
105 | return ftime;
106 | }
107 |
108 | /**
109 | * 判断给定字符串时间是否为今日
110 | *
111 | * @param sdate
112 | * @return boolean
113 | */
114 | public static boolean isToday(String sdate) {
115 | boolean b = false;
116 | Date time = toDate(sdate);
117 | Date today = new Date();
118 | if (time != null) {
119 | String nowDate = dateFormater2.get().format(today);
120 | String timeDate = dateFormater2.get().format(time);
121 | if (nowDate.equals(timeDate)) {
122 | b = true;
123 | }
124 | }
125 | return b;
126 | }
127 |
128 | /**
129 | * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串,返回true
130 | *
131 | * @param input
132 | * @return boolean
133 | */
134 | public static boolean isEmpty(String input) {
135 | if (input == null || "".equals(input))
136 | return true;
137 |
138 | for (int i = 0; i < input.length(); i++) {
139 | char c = input.charAt(i);
140 | if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
141 | return false;
142 | }
143 | }
144 | return true;
145 | }
146 |
147 | /**
148 | * URL解码
149 | *
150 | * @param str
151 | * @return
152 | */
153 | public static String decodeURL(String str) {
154 | return URLDecoder.decode(str);
155 | }
156 |
157 | public static String enCodeRUL(String str) {
158 | try {
159 | return URLEncoder.encode(str, "UTF-8");
160 | } catch (Exception ex) {
161 | }
162 | return str;
163 | }
164 |
165 | public static boolean isEmpty(Object str) {
166 | return str == null || str.toString().length() == 0;
167 | }
168 |
169 | public static boolean isNotEmpty(Object str) {
170 | return !isEmpty(str);
171 | }
172 |
173 | /* 去掉时间为00:00:00 */
174 | public static String replaceTimeZero(String date) {
175 | if (date != null) {
176 | if (date.indexOf("00:00:00") > 0) {
177 | date = date.replaceAll("00:00:00", "");
178 | } else if (date.indexOf(":00") == 16) {
179 | date = date.substring(0, 16);
180 | }
181 | }
182 | return date;
183 | }
184 |
185 | public static boolean startWithHttp(Object str) {
186 | return str != null
187 | && str.toString().toLowerCase().startsWith("http://");
188 | }
189 |
190 | /* 字符串截取 防止出现半个汉字 */
191 | public static String truncate(String str, int byteLength) {
192 | if (str == null) {
193 | return null;
194 | }
195 | if (str.length() == 0) {
196 | return str;
197 | }
198 | if (byteLength < 0) {
199 | throw new IllegalArgumentException(
200 | "Parameter byteLength must be great than 0");
201 | }
202 | int i = 0;
203 | int len = 0;
204 | int leng = 0;
205 | char[] chs = str.toCharArray();
206 | try {
207 | leng = str.getBytes("gbk").length;
208 |
209 | } catch (UnsupportedEncodingException e) {
210 | e.printStackTrace();
211 | }
212 | if (leng <= byteLength)
213 | return str;
214 | while ((len < byteLength) && (i < leng)) {
215 | len = (chs[i++] > 0xff) ? (len + 2) : (len + 1);
216 | }
217 |
218 | if (len > byteLength) {
219 | i--;
220 | }
221 | return new String(chs, 0, i) + "...";
222 | }
223 |
224 | /**
225 | * 分割keyword 按最后一个出现的@分割
226 | *
227 | * @param data
228 | * @return keyword
229 | */
230 | public static String splitKeyWord(String data) {
231 | if (data == null || data.length() == 0)
232 | return null;
233 | if (data.lastIndexOf("@") == -1)
234 | return data;
235 | return data.substring(0, data.lastIndexOf("@"));
236 | }
237 |
238 | /**
239 | * @param date (时间戳)
240 | * @return 年-月-日 (2013-03-01)
241 | */
242 | public static String convertDate(String date) {
243 | try {
244 | if (date == null || "".equals(date))
245 | return "";
246 | if (isNumeric(date))
247 | return computingTime(Long.parseLong(date));
248 | else
249 | return date;
250 | } catch (Exception e) {
251 | return "";
252 | }
253 | }
254 |
255 | /**
256 | * 确定是否是时间戳
257 | *
258 | * @param str
259 | * @return
260 | */
261 | private static boolean isNumeric(String str) {
262 | if (str == null || "".equals(str))
263 | return false;
264 | Pattern pattern = Pattern.compile("[0-9]*");
265 | Matcher isNum = pattern.matcher(str);
266 | if (!isNum.matches()) {
267 | return false;
268 | }
269 | return true;
270 |
271 | }
272 |
273 | /**
274 | * 计算时间1-59分钟前,
275 | *
276 | * @param date
277 | * @return
278 | */
279 | private static String computingTime(Long date) {
280 | if (date < 10000)
281 | return "";
282 | long currentTime = System.currentTimeMillis();
283 | float i = ((currentTime - date) / 3600 / 1000);
284 | if (i < 1) {
285 | int time = (int) Math.ceil(i * 60);
286 | return time + 1 + "分钟前";
287 | } else if (i < 24) {
288 | return (int) i + "小时前";
289 | } else if (i < 48)
290 | return "昨天";
291 | return toNYR(date);
292 | }
293 |
294 | /**
295 | * 截取年月日 如(2013-01-08)
296 | *
297 | * @param data
298 | * @return yyyy-MM-dd
299 | */
300 | private static String toNYR(long data) {
301 | SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-M-d");
302 | try {
303 | return dateFormat.format(data);
304 | } catch (Exception e) {
305 | return "";
306 | }
307 | }
308 |
309 | /**
310 | * 抽正文标题
311 | *
312 | * @param str
313 | * @return
314 | */
315 | public static String setReadabilityTitle(String str) {
316 | String res = null;
317 | if (str != null)
318 | if (str.length() > 9)
319 | res = str.substring(0, 3) + "..."
320 | + str.substring(str.length() - 3, str.length());
321 | return res == null ? str : res;
322 | }
323 |
324 | /**
325 | * 字符串转整数
326 | *
327 | * @param str
328 | * @param defValue
329 | * @return
330 | */
331 | public static int toInt(String str, int defValue) {
332 | try {
333 | return Integer.parseInt(str);
334 | } catch (Exception e) {
335 | }
336 | return defValue;
337 | }
338 |
339 | /**
340 | * 对象转整数
341 | *
342 | * @param obj
343 | * @return 转换异常返回 0
344 | */
345 | public static int toInt(Object obj) {
346 | if (obj == null)
347 | return 0;
348 | return toInt(obj.toString(), 0);
349 | }
350 |
351 | /**
352 | * 对象转整数
353 | *
354 | * @param obj
355 | * @return 转换异常返回 0
356 | */
357 | public static long toLong(String obj) {
358 | try {
359 | return Long.parseLong(obj);
360 | } catch (Exception e) {
361 | }
362 | return 0;
363 | }
364 |
365 | /**
366 | * 字符串转布尔值
367 | *
368 | * @param b
369 | * @return 转换异常返回 false
370 | */
371 | public static boolean toBool(String b) {
372 | try {
373 | return Boolean.parseBoolean(b);
374 | } catch (Exception e) {
375 | }
376 | return false;
377 | }
378 |
379 | /**
380 | * 将list中的字符串用split间隔开
381 | *
382 | * @param list
383 | * @param split
384 | * @return
385 | */
386 | public static String Join(List list, String split) {
387 | StringBuilder sb = new StringBuilder();
388 | for (int i = 0; i < list.size(); i++) {
389 | sb.append(list.get(i));
390 | if (i + 1 != list.size()) {
391 | sb.append(split);
392 | }
393 | }
394 | return sb.toString();
395 | }
396 |
397 | @Deprecated
398 | public static String toPriceStr(double price) {
399 | return "¥" + numberFormat.format(price);
400 | }
401 |
402 | public static String toDateString(Date date) {
403 | return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
404 | }
405 |
406 |
407 | /**
408 | * 流转字符串方法
409 | *
410 | * @param is
411 | * @return
412 | */
413 | public static String convertStreamToString(InputStream is) {
414 | BufferedReader reader = new BufferedReader(new InputStreamReader(is));
415 | StringBuilder sb = new StringBuilder();
416 | String line = null;
417 | try {
418 | while ((line = reader.readLine()) != null) {
419 | sb.append(line);
420 | }
421 | } catch (IOException e) {
422 | e.printStackTrace();
423 | } finally {
424 | try {
425 | is.close();
426 | } catch (IOException e) {
427 | e.printStackTrace();
428 | }
429 | }
430 | return sb.toString();
431 | }
432 |
433 | }
434 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/utils/UIUtils.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.utils;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.view.WindowManager;
6 |
7 | public class UIUtils {
8 |
9 | public static void lightOn(Activity activity) {
10 | WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
11 | lp.alpha = 1.0f;
12 | activity.getWindow().setAttributes(lp);
13 | }
14 |
15 | public static void lightOff(Activity activity){
16 | WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
17 | lp.alpha = 0.3f;
18 | activity.getWindow().setAttributes(lp);
19 | }
20 |
21 |
22 | /**
23 | * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
24 | */
25 | public static int dip2px(Context context, float dpValue) {
26 | final float scale = context.getResources().getDisplayMetrics().density;
27 | return (int) (dpValue * scale + 0.5f);
28 | }
29 |
30 | /**
31 | * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
32 | */
33 | public static int px2dip(Context context, float pxValue) {
34 | final float scale = context.getResources().getDisplayMetrics().density;
35 | return (int) (pxValue / scale + 0.5f);
36 | }
37 |
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/volley/BitmapCache.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.volley;
2 |
3 | import android.graphics.Bitmap;
4 | import android.util.LruCache;
5 |
6 | import com.android.volley.toolbox.ImageLoader;
7 |
8 | public class BitmapCache implements ImageLoader.ImageCache {
9 | private LruCache mCache;
10 |
11 | public BitmapCache() {
12 | int maxSize = 10 * 1024 * 1024;
13 | mCache = new LruCache(maxSize) {
14 | @Override
15 | protected int sizeOf(String key, Bitmap bitmap) {
16 | return bitmap.getRowBytes() * bitmap.getHeight();
17 | }
18 | };
19 | }
20 |
21 | @Override
22 | public Bitmap getBitmap(String url) {
23 | return mCache.get(url);
24 | }
25 |
26 | @Override
27 | public void putBitmap(String url, Bitmap bitmap) {
28 | mCache.put(url, bitmap);
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/volley/MyStringRequest.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.volley;
2 |
3 | import com.android.volley.NetworkResponse;
4 | import com.android.volley.Response;
5 | import com.android.volley.toolbox.HttpHeaderParser;
6 |
7 | import java.io.UnsupportedEncodingException;
8 |
9 | public class MyStringRequest extends StringRequest {
10 |
11 | public MyStringRequest(int method, String url, Response.Listener listener, Response.ErrorListener errorListener) {
12 | super(method, url, listener, errorListener);
13 | }
14 |
15 | /**
16 | * 重写以解决乱码问题
17 | */
18 | @Override
19 | protected Response parseNetworkResponse(NetworkResponse response) {
20 | String str = null;
21 | try {
22 | str = new String(response.data, "utf-8");
23 | } catch (UnsupportedEncodingException e) {
24 | e.printStackTrace();
25 | }
26 | return Response.success(str, HttpHeaderParser.parseCacheHeaders(response));
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/volley/StringRequest.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.volley;
2 |
3 | import com.android.volley.NetworkResponse;
4 | import com.android.volley.Request;
5 | import com.android.volley.Response;
6 | import com.android.volley.toolbox.HttpHeaderParser;
7 |
8 | import java.io.UnsupportedEncodingException;
9 |
10 | public class StringRequest extends Request {
11 | private final Response.Listener mListener;
12 |
13 | public StringRequest(int method, String url, Response.Listener listener, Response.ErrorListener errorListener) {
14 | super(method, url, errorListener);
15 | this.mListener = listener;
16 | }
17 |
18 | public StringRequest(String url, Response.Listener listener, Response.ErrorListener errorListener) {
19 | this(0, url, listener, errorListener);
20 | }
21 |
22 | protected void deliverResponse(String response) {
23 | this.mListener.onResponse(response);
24 | }
25 |
26 | protected Response parseNetworkResponse(NetworkResponse response) {
27 | String parsed;
28 | try {
29 | parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
30 | } catch (UnsupportedEncodingException var4) {
31 | parsed = new String(response.data);
32 | }
33 |
34 | return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/volley/VolleyByGet.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.volley;
2 |
3 | import android.content.Context;
4 | import android.graphics.Bitmap;
5 | import android.util.Log;
6 | import android.widget.ImageView;
7 |
8 | import com.android.volley.AuthFailureError;
9 | import com.android.volley.Request;
10 | import com.android.volley.RequestQueue;
11 | import com.android.volley.Response;
12 | import com.android.volley.VolleyError;
13 | import com.android.volley.toolbox.ImageLoader;
14 | import com.android.volley.toolbox.ImageRequest;
15 | import com.android.volley.toolbox.JsonArrayRequest;
16 | import com.android.volley.toolbox.JsonObjectRequest;
17 | import com.android.volley.toolbox.NetworkImageView;
18 | import com.android.volley.toolbox.StringRequest;
19 | import com.android.volley.toolbox.Volley;
20 | import com.frank.ycj520.networkrequest.R;
21 |
22 | import org.json.JSONArray;
23 | import org.json.JSONObject;
24 | import org.xmlpull.v1.XmlPullParser;
25 | import org.xmlpull.v1.XmlPullParserException;
26 |
27 | import java.io.IOException;
28 | import java.util.Map;
29 |
30 | public class VolleyByGet {
31 |
32 |
33 | /*
34 | 安全连接:
35 | 方法一:
36 | 使用证书进行构建连接如下:
37 |
38 | RequestQueue requestQueue =Volley.newRequestQueue(getApplicationContext());//使用https连接
39 | 或者
40 | SSLSocketFactory sslSocketFactory =initSSLSocketFactory();
41 | HurlStack stack = new HurlStack(null,sslSocketFactory);
42 | RequestQueue requestQueue =Volley.newRequestQueue(mContext, stack);
43 |
44 | 方法二:
45 | 在创建请求Request对象前加上一行代码:SsX509TrustManager.allowAllSSL();即可,如:
46 | RequestQueue requestQueue =Volley.newRequestQueue(getApplicationContext());
47 | SsX509TrustManager.allowAllSSL();
48 | StringRequest stringRequest = newStringRequest(Request.Method.GET, "https://kyfw.12306.cn/otn/regist/init",
49 | new Response.Listener() {
50 | @Override
51 | public void onResponse(String s) {
52 | // 请求成功
53 | }
54 | },
55 | new Response.ErrorListener() {
56 | @Override
57 | public void onErrorResponse(VolleyError volleyError) {
58 | // 请求失败
59 | }
60 | });
61 | requestQueue.add(stringRequest);
62 |
63 | */
64 |
65 |
66 | public static void requestByGet(Context context,String url,Response.Listener responseListener,Response.ErrorListener errorListener){
67 | //创建请求队列
68 | RequestQueue mQueue = Volley.newRequestQueue(context);
69 | StringRequest mStringRequest = new StringRequest(Request.Method.GET, url,responseListener,errorListener);
70 | //将请求添加在请求队列中
71 | mQueue.add(mStringRequest);
72 |
73 | }
74 |
75 | public static void requestByGetAddHeaders(Context context,String url,final Map mapHeaders,Response.Listener responseListener,Response.ErrorListener errorListener){
76 | //创建请求队列
77 | RequestQueue mQueue = Volley.newRequestQueue(context);
78 | StringRequest mStringRequest = new StringRequest(Request.Method.GET, url,responseListener,errorListener){
79 | @Override
80 | public Map getHeaders() throws AuthFailureError {
81 | return mapHeaders;
82 | }
83 | };
84 | //将请求添加在请求队列中
85 | mQueue.add(mStringRequest);
86 |
87 | }
88 |
89 | public static void requestByTag(Context context, String url, Response.Listener listener, Response.ErrorListener errorListener, Object tag) {
90 | RequestQueue mQueue = Volley.newRequestQueue(context);
91 | MyStringRequest request = new MyStringRequest(Request.Method.GET, url, listener, errorListener);
92 | request.setTag(tag);
93 | mQueue.add(request);
94 | }
95 |
96 | public static void requestByTagAddHeaders(Context context, String url,final Map mapHeaders, Response.Listener listener, Response.ErrorListener errorListener, Object tag) {
97 | RequestQueue mQueue = Volley.newRequestQueue(context);
98 | MyStringRequest request = new MyStringRequest(Request.Method.GET, url, listener, errorListener){
99 | @Override
100 | public Map getHeaders() throws AuthFailureError {
101 | return mapHeaders;
102 | }
103 | };
104 | request.setTag(tag);
105 | mQueue.add(request);
106 | }
107 |
108 | public static void requestByPostJSONObject(Context context,String url, Response.Listener responseListener, Response.ErrorListener errorListener){
109 | final RequestQueue mQueue = Volley.newRequestQueue(context);
110 | JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,(String)null,responseListener,errorListener);
111 | mQueue.add(jsonObjectRequest);
112 |
113 | }
114 |
115 | public static void requestByPostJSONObjectAddHeaders(Context context,String url,final Map mapHeaders,Response.Listener responseListener, Response.ErrorListener errorListener){
116 | final RequestQueue mQueue = Volley.newRequestQueue(context);
117 | JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,(String)null,responseListener,errorListener){
118 | @Override
119 | public Map getHeaders() throws AuthFailureError {
120 | return mapHeaders;
121 | }
122 | };
123 | mQueue.add(jsonObjectRequest);
124 |
125 | }
126 |
127 | public static void requestByPostJSONArray(Context context, String url, Response.Listener responseListener, Response.ErrorListener errorListener){
128 | //队列初始化以及request加入队列略
129 | RequestQueue mQueue = Volley.newRequestQueue(context);
130 | JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,url,responseListener,errorListener);
131 | mQueue.add(jsonArrayRequest);
132 | }
133 |
134 | public static void requestByPostJSONArrayAddHeaders(Context context, String url,final Map mapHeaders, Response.Listener responseListener, Response.ErrorListener errorListener){
135 | //队列初始化以及request加入队列略
136 | RequestQueue mQueue = Volley.newRequestQueue(context);
137 | JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,url,responseListener,errorListener){
138 | @Override
139 | public Map getHeaders() throws AuthFailureError {
140 | return mapHeaders;
141 | }
142 | };
143 | mQueue.add(jsonArrayRequest);
144 | }
145 |
146 | public static void requestByGetJson(Context context,String url,Response.Listener responseListener,Response.ErrorListener errorListener){
147 | RequestQueue mQueue = Volley.newRequestQueue(context);
148 | JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Request.Method.GET,url ,responseListener,errorListener
149 | );
150 | mQueue.add(mJsonObjectRequest);
151 |
152 | }
153 |
154 | public static void requestByGetJsonAddHeaders(Context context,String url,final Map mapHeaders,Response.Listener responseListener,Response.ErrorListener errorListener){
155 | RequestQueue mQueue = Volley.newRequestQueue(context);
156 | JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Request.Method.GET,url ,responseListener,errorListener){
157 | @Override
158 | public Map getHeaders() throws AuthFailureError {
159 | return mapHeaders;
160 | }
161 | };
162 | mQueue.add(mJsonObjectRequest);
163 |
164 | }
165 |
166 |
167 |
168 | //自定义xml解析
169 | public static void requestByXmlRequest(Context context,String url,Response.Listener responseListener,Response.ErrorListener errorListener){
170 | RequestQueue mQueue= Volley.newRequestQueue(context);
171 | XMLRequest xmlr=new XMLRequest(url,responseListener,errorListener);
172 | mQueue.add(xmlr);
173 | }
174 | }
175 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/volley/VolleyByImage.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.volley;
2 |
3 | import android.content.Context;
4 | import android.graphics.Bitmap;
5 | import android.widget.ImageView;
6 |
7 | import com.android.volley.RequestQueue;
8 | import com.android.volley.Response;
9 | import com.android.volley.toolbox.ImageLoader;
10 | import com.android.volley.toolbox.ImageRequest;
11 | import com.android.volley.toolbox.NetworkImageView;
12 | import com.android.volley.toolbox.Volley;
13 |
14 | public class VolleyByImage {
15 |
16 | /*
17 | 第三/四个参数用于指定允许图片最大的宽/高,若网络图片的实际宽高大于该设定值,则会对图片进行压缩,指定成0的话就表示不进行压缩。
18 | 第五个参数用于指定图片的颜色属性,Bitmap.Config下的几个常量都可以在这里使用,其中ARGB_8888可以展示最好的颜色属性,
19 | 每个图片像素占据4个字节的大小,而RGB_565则表示每个图片像素占据2个字节大小。
20 | */
21 | public static void loadImageByImageRequest(Context context, String url, Response.Listener responseListener, Response.ErrorListener errorListener){
22 | RequestQueue mQueue = Volley.newRequestQueue(context);
23 | ImageRequest imageRequest = new ImageRequest(url, responseListener, 0, 0, Bitmap.Config.RGB_565,errorListener);
24 | mQueue.add(imageRequest);
25 |
26 | }
27 |
28 | //查看ImageRequest的源码发现它可以设置你想要的图片的最大宽度和高度,在加载图片时如果图片超过期望的最大宽度和高度则会进行压缩
29 | public static void loadImageByImageRequest(Context context,String url,Response.Listener responseListener,int maxWidth, int maxHeight,Response.ErrorListener errorListener){
30 | RequestQueue mQueue = Volley.newRequestQueue(context);
31 | ImageRequest imageRequest = new ImageRequest(url, responseListener, maxWidth, maxHeight, Bitmap.Config.RGB_565,errorListener);
32 | mQueue.add(imageRequest);
33 |
34 | }
35 |
36 | //查看ImageRequest的源码发现它可以设置你想要的图片的最大宽度和高度,在加载图片时如果图片超过期望的最大宽度和高度则会进行压缩
37 | public static void loadImageByImageRequest(Context context, String url, final ImageView imageView, int maxWidth, int maxHeight, Response.ErrorListener errorListener){
38 | RequestQueue mQueue = Volley.newRequestQueue(context);
39 | ImageRequest imageRequest = new ImageRequest(
40 | url,
41 | new Response.Listener() {
42 | @Override
43 | public void onResponse(Bitmap response) {
44 | imageView.setImageBitmap(response);
45 | }
46 | }, maxWidth, maxHeight, Bitmap.Config.RGB_565, errorListener);
47 | mQueue.add(imageRequest);
48 |
49 | }
50 |
51 | //查看ImageRequest的源码发现它可以设置你想要的图片的最大宽度和高度,在加载图片时如果图片超过期望的最大宽度和高度则会进行压缩
52 | public static void loadImageByImageRequest(Context context, String url, final ImageView imageView, Response.ErrorListener errorListener){
53 | RequestQueue mQueue = Volley.newRequestQueue(context);
54 | ImageRequest imageRequest = new ImageRequest(
55 | url,
56 | new Response.Listener() {
57 | @Override
58 | public void onResponse(Bitmap response) {
59 | imageView.setImageBitmap(response);
60 | }
61 | }, 0, 0, Bitmap.Config.RGB_565, errorListener);
62 | mQueue.add(imageRequest);
63 |
64 | }
65 |
66 | //ImageLoader的内部使用ImageRequest来实现,它的构造器可以传入一个ImageCache缓存形参,实现了图片缓存的功能,同时还可以过滤重复链接,避免重复发送请求。
67 | //与ImageRequest实现效果不同的是,ImageLoader加载图片会先显示默认的图片,等待图片加载完成才会显示在ImageView上。
68 | public static void loadImageByImageLoader(Context context,String url,ImageView imageView, final int defaultImageResId, final int errorImageResId){
69 | RequestQueue mQueue = Volley.newRequestQueue(context);
70 | ImageLoader imageLoader = new ImageLoader(mQueue, new BitmapCache());
71 | ImageLoader.ImageListener listener = ImageLoader.getImageListener(imageView,defaultImageResId, errorImageResId);
72 | imageLoader.get(url, listener);
73 | }
74 |
75 | public static void loadImageByImageLoader(Context context,String url,ImageView imageView,int maxWidth, int maxHeight,final int defaultImageResId, final int errorImageResId){
76 | RequestQueue mQueue = Volley.newRequestQueue(context);
77 | ImageLoader imageLoader = new ImageLoader(mQueue, new BitmapCache());
78 | ImageLoader.ImageListener listener = ImageLoader.getImageListener(imageView,defaultImageResId, errorImageResId);
79 | imageLoader.get(url, listener);
80 | imageLoader.get(url,listener, maxWidth, maxHeight);
81 | }
82 |
83 |
84 | public static void loadImageByNetworkImageView(Context context, String url, NetworkImageView networkImageView, final int defaultImageResId, final int errorImageResId){
85 | RequestQueue mQueue= Volley.newRequestQueue(context);
86 | ImageLoader imageLoader=new ImageLoader(mQueue,new BitmapCache());
87 | networkImageView.setDefaultImageResId(defaultImageResId);//加载中显示的图片
88 | networkImageView.setErrorImageResId(errorImageResId);//加载错误时显示的图片
89 | networkImageView.setImageUrl(url,imageLoader);
90 | }
91 |
92 | }
93 |
--------------------------------------------------------------------------------
/networkrequest/src/main/java/com/frank/ycj520/networkrequest/volley/VolleyByPost.java:
--------------------------------------------------------------------------------
1 | package com.frank.ycj520.networkrequest.volley;
2 |
3 | import android.content.Context;
4 |
5 | import com.android.volley.AuthFailureError;
6 | import com.android.volley.Request;
7 | import com.android.volley.RequestQueue;
8 | import com.android.volley.Response;
9 | import com.android.volley.toolbox.JsonArrayRequest;
10 | import com.android.volley.toolbox.JsonObjectRequest;
11 | import com.android.volley.toolbox.Volley;
12 |
13 | import org.json.JSONArray;
14 | import org.json.JSONObject;
15 | import org.xmlpull.v1.XmlPullParser;
16 |
17 | import java.util.Map;
18 |
19 | public class VolleyByPost {
20 |
21 | /*
22 | 安全连接:
23 | 方法一:
24 | 使用证书进行构建连接如下:
25 |
26 | RequestQueue requestQueue =Volley.newRequestQueue(getApplicationContext());//使用https连接
27 | 或者
28 | SSLSocketFactory sslSocketFactory =initSSLSocketFactory();
29 | HurlStack stack = new HurlStack(null,sslSocketFactory);
30 | RequestQueue requestQueue =Volley.newRequestQueue(mContext, stack);
31 |
32 | 方法二:
33 | 在创建请求Request对象前加上一行代码:SsX509TrustManager.allowAllSSL();即可,如:
34 | RequestQueue requestQueue =Volley.newRequestQueue(getApplicationContext());
35 | SsX509TrustManager.allowAllSSL();
36 | StringRequest stringRequest = newStringRequest(Request.Method.GET, "https://kyfw.12306.cn/otn/regist/init",
37 | new Response.Listener() {
38 | @Override
39 | public void onResponse(String s) {
40 | // 请求成功
41 | }
42 | },
43 | new Response.ErrorListener() {
44 | @Override
45 | public void onErrorResponse(VolleyError volleyError) {
46 | // 请求失败
47 | }
48 | });
49 | requestQueue.add(stringRequest);
50 |
51 | */
52 |
53 |
54 | public static void requestByPostString(Context context, String url, final Map map, Response.Listener responseListener, Response.ErrorListener errorListener){
55 | RequestQueue mQueue = Volley.newRequestQueue(context);
56 | StringRequest stringRequest = new StringRequest(Request.Method.POST, url, responseListener, errorListener) {
57 | @Override
58 | protected Map getParams() throws AuthFailureError {
59 | return map;
60 | }
61 | };
62 | mQueue.add(stringRequest);
63 |
64 | }
65 |
66 | public static void requestByPostStringAddHeaders(Context context, String url,final Map mapHeaders, final Map map, Response.Listener responseListener, Response.ErrorListener errorListener){
67 | RequestQueue mQueue = Volley.newRequestQueue(context);
68 | StringRequest stringRequest = new StringRequest(Request.Method.POST, url, responseListener, errorListener) {
69 | @Override
70 | protected Map getParams() throws AuthFailureError {
71 | return map;
72 | }
73 |
74 | @Override
75 | public Map getHeaders() throws AuthFailureError {
76 | return mapHeaders;
77 | }
78 | };
79 | mQueue.add(stringRequest);
80 |
81 | }
82 |
83 | public static void requestByPUT(Context context, String url, Response.Listener listener, Response.ErrorListener errorListener) {
84 | RequestQueue mQueue = Volley.newRequestQueue(context);
85 | mQueue.add(new MyStringRequest(Request.Method.PUT, url, listener, errorListener));
86 | }
87 |
88 | public static void requestByPUTAddHeaders(Context context, String url,final Map mapHeaders, Response.Listener listener, Response.ErrorListener errorListener) {
89 | RequestQueue mQueue = Volley.newRequestQueue(context);
90 | mQueue.add(new MyStringRequest(Request.Method.PUT, url, listener, errorListener){
91 | @Override
92 | public Map getHeaders() throws AuthFailureError {
93 | return mapHeaders;
94 | }
95 | });
96 | }
97 |
98 | public static void requestByDELETE(Context context, String url, Response.Listener listener, Response.ErrorListener errorListener) {
99 | RequestQueue mQueue = Volley.newRequestQueue(context);
100 | mQueue.add(new MyStringRequest(Request.Method.DELETE, url, listener, errorListener));
101 | }
102 |
103 | public static void requestByDELETEAddHeaders(Context context, String url,final Map mapHeaders, Response.Listener listener, Response.ErrorListener errorListener) {
104 | RequestQueue mQueue = Volley.newRequestQueue(context);
105 | mQueue.add(new MyStringRequest(Request.Method.DELETE, url, listener, errorListener){
106 | @Override
107 | public Map getHeaders() throws AuthFailureError {
108 | return mapHeaders;
109 | }
110 | });
111 | }
112 |
113 |
114 | public static void requestByPostJSONObject(Context context, String url,Response.Listener responseListener, Response.ErrorListener errorListener){
115 | //队列初始化以及request加入队列略
116 | RequestQueue mQueue = Volley.newRequestQueue(context);
117 | JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, responseListener,errorListener);
118 | mQueue.add(jsonObjectRequest);
119 | }
120 |
121 | public static void requestByPostJSONObjectAddHeaders(Context context, String url,final Map mapHeaders,Response.Listener responseListener, Response.ErrorListener errorListener){
122 | //队列初始化以及request加入队列略
123 | RequestQueue mQueue = Volley.newRequestQueue(context);
124 | JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, responseListener,errorListener){
125 | @Override
126 | public Map getHeaders() throws AuthFailureError {
127 | return mapHeaders;
128 | }
129 | };
130 | mQueue.add(jsonObjectRequest);
131 | }
132 |
133 | public static void requestByPostJSONObject(Context context, String url,Map map,Response.Listener responseListener, Response.ErrorListener errorListener){
134 | //队列初始化以及request加入队列略
135 | RequestQueue mQueue = Volley.newRequestQueue(context);
136 | JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url, new JSONObject(map),responseListener,errorListener);
137 | mQueue.add(jsonObjectRequest);
138 | }
139 |
140 | public static void requestByPostJSONObjectAddHeaders(Context context, String url, Map mapData, final Map mapHeaders, Response.Listener responseListener, Response.ErrorListener errorListener){
141 | //队列初始化以及request加入队列略
142 | final RequestQueue mQueue = Volley.newRequestQueue(context);
143 | final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url, new JSONObject(mapData),responseListener,errorListener) {
144 | @Override
145 | public Map getHeaders() throws AuthFailureError {
146 | return mapHeaders;
147 | }
148 | };
149 |
150 | mQueue.add(jsonObjectRequest);
151 | }
152 |
153 | public static void requestByPostJSONArray(Context context, String url, Response.Listener responseListener, Response.ErrorListener errorListener){
154 | //队列初始化以及request加入队列略
155 | RequestQueue mQueue = Volley.newRequestQueue(context);
156 | JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,url,responseListener,errorListener);
157 | mQueue.add(jsonArrayRequest);
158 | }
159 |
160 | public static void requestByPostJSONArrayAddHeaders(Context context, String url,final Map mapHeaders, Response.Listener responseListener, Response.ErrorListener errorListener){
161 | //队列初始化以及request加入队列略
162 | RequestQueue mQueue = Volley.newRequestQueue(context);
163 | JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,url,responseListener,errorListener){
164 | @Override
165 | public Map getHeaders() throws AuthFailureError {
166 | return mapHeaders;
167 | }
168 | };
169 | mQueue.add(jsonArrayRequest);
170 | }
171 |
172 | public static void requestByGetJson(Context context,String url,Response.Listener responseListener,Response.ErrorListener errorListener){
173 | RequestQueue mQueue = Volley.newRequestQueue(context);
174 | JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url ,responseListener,errorListener);
175 | mQueue.add(mJsonObjectRequest);
176 |
177 | }
178 |
179 | public static void requestByGetJsonAddHeaders(Context context,String url,final Map mapHeaders,Response.Listener responseListener,Response.ErrorListener errorListener){
180 | RequestQueue mQueue = Volley.newRequestQueue(context);
181 | JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url ,responseListener,errorListener){
182 | @Override
183 | public Map getHeaders() throws AuthFailureError {
184 | return mapHeaders;
185 | }
186 | };
187 | mQueue.add(mJsonObjectRequest);
188 |
189 | }
190 |
191 | /*public static void requestByGsonRequest(String url, Class beanClass, Class changeClass, Response.Listener