├── andnet
├── .gitignore
├── src
│ ├── main
│ │ ├── java
│ │ │ └── org
│ │ │ │ └── loader
│ │ │ │ └── andnet
│ │ │ │ ├── helper
│ │ │ │ ├── IBaseBean.java
│ │ │ │ ├── Annotation.java
│ │ │ │ └── Helper.java
│ │ │ │ ├── net
│ │ │ │ ├── Result.java
│ │ │ │ ├── RequestParams.java
│ │ │ │ ├── INetStack.java
│ │ │ │ ├── AbsHttpStack.java
│ │ │ │ └── Net.java
│ │ │ │ └── okhttp
│ │ │ │ └── OkHttpStack.java
│ │ └── AndroidManifest.xml
│ └── androidTest
│ │ └── java
│ │ └── org
│ │ └── loader
│ │ └── andnet
│ │ └── ApplicationTest.java
├── build.gradle
├── proguard-rules.pro
└── andnet.iml
├── samples
├── .gitignore
├── libs
│ ├── volley.jar
│ └── fastjson-1.1.43.android.jar
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── mipmap-hdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ ├── dimens.xml
│ │ │ │ └── styles.xml
│ │ │ ├── menu
│ │ │ │ └── menu_main.xml
│ │ │ └── layout
│ │ │ │ └── activity_main.xml
│ │ ├── java
│ │ │ ├── org
│ │ │ │ └── loader
│ │ │ │ │ └── nettest
│ │ │ │ │ ├── OkHttpHeaderStack.java
│ │ │ │ │ ├── App.java
│ │ │ │ │ ├── User.java
│ │ │ │ │ ├── CommParser.java
│ │ │ │ │ ├── ListParser.java
│ │ │ │ │ └── MainActivity.java
│ │ │ └── volley
│ │ │ │ ├── VolleyManager.java
│ │ │ │ └── VolleyStack.java
│ │ └── AndroidManifest.xml
│ └── androidTest
│ │ └── java
│ │ └── org
│ │ └── loader
│ │ └── nettest
│ │ └── ApplicationTest.java
├── proguard-rules.pro
├── build.gradle
├── simples.iml
└── nettest.iml
├── jar
└── org.loader.andnet.jar
├── .gitignore
├── README.md
└── LICENSE
/andnet/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/samples/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/samples/libs/volley.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qibin0506/AndNet/HEAD/samples/libs/volley.jar
--------------------------------------------------------------------------------
/jar/org.loader.andnet.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qibin0506/AndNet/HEAD/jar/org.loader.andnet.jar
--------------------------------------------------------------------------------
/samples/libs/fastjson-1.1.43.android.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qibin0506/AndNet/HEAD/samples/libs/fastjson-1.1.43.android.jar
--------------------------------------------------------------------------------
/samples/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qibin0506/AndNet/HEAD/samples/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/samples/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qibin0506/AndNet/HEAD/samples/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/samples/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qibin0506/AndNet/HEAD/samples/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/samples/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qibin0506/AndNet/HEAD/samples/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/samples/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/qibin0506/AndNet/HEAD/samples/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/samples/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | NetTest
3 | Settings
4 |
5 |
--------------------------------------------------------------------------------
/andnet/src/main/java/org/loader/andnet/helper/IBaseBean.java:
--------------------------------------------------------------------------------
1 | package org.loader.andnet.helper;
2 |
3 | /**
4 | * Created by qibin on 2015/11/29.
5 | */
6 | public interface IBaseBean {
7 | }
8 |
--------------------------------------------------------------------------------
/samples/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/andnet/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/samples/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 | 16dp
6 |
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 |
15 | # Gradle files
16 | .gradle/
17 | build/
18 | /*/build/
19 |
20 | # Local configuration file (sdk path, etc)
21 | local.properties
22 |
23 | # Proguard folder generated by Eclipse
24 | proguard/
25 |
26 | # Log Files
27 | *.log
28 |
--------------------------------------------------------------------------------
/andnet/src/androidTest/java/org/loader/andnet/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package org.loader.andnet;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/samples/src/androidTest/java/org/loader/nettest/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package org.loader.nettest;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/samples/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/andnet/src/main/java/org/loader/andnet/helper/Annotation.java:
--------------------------------------------------------------------------------
1 | package org.loader.andnet.helper;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 | import java.lang.annotation.Target;
7 |
8 | /**
9 | * Created by qibin on 2015/11/29.
10 | */
11 |
12 | @Target(ElementType.FIELD)
13 | @Retention(RetentionPolicy.RUNTIME)
14 | public @interface Annotation {
15 | String key();
16 | }
17 |
--------------------------------------------------------------------------------
/samples/src/main/res/menu/menu_main.xml:
--------------------------------------------------------------------------------
1 |
11 |
--------------------------------------------------------------------------------
/samples/src/main/java/org/loader/nettest/OkHttpHeaderStack.java:
--------------------------------------------------------------------------------
1 | package org.loader.nettest;
2 |
3 |
4 | import org.loader.andnet.okhttp.OkHttpStack;
5 |
6 | import java.util.LinkedHashMap;
7 |
8 | /**
9 | * Created by lenovo on 2015/11/30.
10 | */
11 | public class OkHttpHeaderStack extends OkHttpStack {
12 |
13 | @Override
14 | public LinkedHashMap headers() {
15 | LinkedHashMap headers = new LinkedHashMap<>();
16 | headers.put("name", "header");
17 | return headers;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/samples/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
10 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/samples/src/main/java/org/loader/nettest/App.java:
--------------------------------------------------------------------------------
1 | package org.loader.nettest;
2 |
3 | import android.app.Application;
4 |
5 |
6 | import org.loader.andnet.net.Net;
7 |
8 | import volley.VolleyStack;
9 |
10 | /**
11 | * Created by lenovo on 2015/11/30.
12 | */
13 | public class App extends Application {
14 |
15 | @Override
16 | public void onCreate() {
17 | super.onCreate();
18 | // Net.init(new VolleyStack(this));
19 | // Net.init(new OkHttpStack());
20 | OkHttpHeaderStack okHttpStack = new OkHttpHeaderStack();
21 | okHttpStack.debug(true);
22 | Net.init(okHttpStack);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/andnet/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | minSdkVersion 9
9 | targetSdkVersion 23
10 | versionCode 1
11 | versionName "1.0"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | }
20 |
21 | dependencies {
22 | compile fileTree(dir: 'libs', include: ['*.jar'])
23 | compile 'com.squareup.okhttp:okhttp:2.0.0'
24 | compile 'com.squareup.okio:okio:1.5.0'
25 | }
26 |
--------------------------------------------------------------------------------
/samples/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/andnet/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\Program Files\studiosdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/samples/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | applicationId "org.loader.nettest"
9 | minSdkVersion 15
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(include: ['*.jar'], dir: 'libs')
24 | testCompile 'junit:junit:4.12'
25 | compile 'com.android.support:appcompat-v7:23.1.1'
26 | compile 'com.android.support:design:23.1.1'
27 | compile project(':andnet')
28 | compile files('libs/fastjson-1.1.43.android.jar')
29 | compile files('libs/volley.jar')
30 | }
31 |
--------------------------------------------------------------------------------
/andnet/src/main/java/org/loader/andnet/net/Result.java:
--------------------------------------------------------------------------------
1 | package org.loader.andnet.net;
2 |
3 | /**
4 | * Created by qibin on 2015/11/29.
5 | */
6 | public class Result {
7 | public static final int ERROR = 0;
8 | public static final int SUCCESS = 1;
9 |
10 | private int status;
11 | private T result;
12 | private String msg;
13 | private Object obj;
14 |
15 | public int getStatus() {
16 | return status;
17 | }
18 |
19 | public void setStatus(int status) {
20 | this.status = status;
21 | }
22 |
23 | public String getMsg() {
24 | return msg;
25 | }
26 |
27 | public void setMsg(String msg) {
28 | this.msg = msg;
29 | }
30 |
31 | public T getResult() {
32 | return result;
33 | }
34 |
35 | public void setResult(T result) {
36 | this.result = result;
37 | }
38 |
39 | public Object getObj() {
40 | return obj;
41 | }
42 |
43 | public void setObj(Object obj) {
44 | this.obj = obj;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/samples/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
15 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/andnet/src/main/java/org/loader/andnet/net/RequestParams.java:
--------------------------------------------------------------------------------
1 | package org.loader.andnet.net;
2 |
3 | import java.io.File;
4 | import java.util.LinkedHashMap;
5 |
6 | /**
7 | * Created by qibin on 2015/11/29.
8 | */
9 | public class RequestParams {
10 | private LinkedHashMap mParams;
11 | private LinkedHashMap mFileParams;
12 |
13 | public RequestParams() {
14 | mParams = new LinkedHashMap();
15 | mFileParams = new LinkedHashMap();
16 | }
17 |
18 | public RequestParams(String key, Object value) {
19 | this();
20 | add(key, value);
21 | }
22 |
23 | public RequestParams add(String key, Object value) {
24 | if(key == null) return this;
25 | if(value == null) mParams.put(key, null);
26 | else if(value instanceof File) mFileParams.put(key, (File) value);
27 | else mParams.put(key, value.toString());
28 | return this;
29 | }
30 |
31 | public LinkedHashMap get() {
32 | return mParams;
33 | }
34 | public LinkedHashMap files() {
35 | return mFileParams;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/samples/src/main/java/org/loader/nettest/User.java:
--------------------------------------------------------------------------------
1 | package org.loader.nettest;
2 |
3 | import org.loader.andnet.helper.Annotation;
4 | import org.loader.andnet.helper.IBaseBean;
5 |
6 | /**
7 | * Created by lenovo on 2015/11/30.
8 | */
9 | public class User implements IBaseBean {
10 | @Annotation(key = "name")
11 | private String name;
12 | @Annotation(key = "age")
13 | private int age;
14 | @Annotation(key = "city")
15 | private String city;
16 |
17 | public String getName() {
18 | return name;
19 | }
20 |
21 | public void setName(String name) {
22 | this.name = name;
23 | }
24 |
25 | public String getCity() {
26 | return city;
27 | }
28 |
29 | public void setCity(String city) {
30 | this.city = city;
31 | }
32 |
33 | public int getAge() {
34 | return age;
35 | }
36 |
37 | public void setAge(int age) {
38 | this.age = age;
39 | }
40 |
41 | @Override
42 | public String toString() {
43 | return "name=" + name + ",age=" + age + ",city=" + city;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/samples/src/main/java/org/loader/nettest/CommParser.java:
--------------------------------------------------------------------------------
1 | package org.loader.nettest;
2 |
3 | import com.alibaba.fastjson.JSON;
4 | import com.alibaba.fastjson.JSONObject;
5 |
6 | import org.loader.andnet.helper.Helper;
7 | import org.loader.andnet.net.Net;
8 | import org.loader.andnet.net.Result;
9 |
10 |
11 | /**
12 | * 共同的parser
13 | *
14 | * @author loader
15 | *
16 | * @param
17 | */
18 | public class CommParser implements Net.Parser {
19 |
20 | private String mKey;
21 |
22 | public CommParser(String key) {
23 | mKey = key;
24 | }
25 |
26 | @Override
27 | public Result parse(String response) {
28 | Result result = new Result();
29 | try {
30 | JSONObject baseObject = JSON.parseObject(response);
31 | if(!baseObject.getBooleanValue("success")) {
32 | result.setMsg(baseObject.getString("message"));
33 | }else {
34 | Class klass = Helper.generateType(getClass());
35 | if(klass == null) throw new Exception();
36 |
37 | T t = baseObject.getObject(mKey, klass);
38 | result.setStatus(Result.SUCCESS);
39 | result.setResult(t);
40 | return result;
41 | }
42 | } catch (Exception e) {
43 | e.printStackTrace();
44 | result.setMsg(Net.ERR_PARSE_MSG);
45 | }
46 |
47 | result.setStatus(Result.ERROR);
48 | return result;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/samples/src/main/java/org/loader/nettest/ListParser.java:
--------------------------------------------------------------------------------
1 | package org.loader.nettest;
2 |
3 | import com.alibaba.fastjson.JSON;
4 | import com.alibaba.fastjson.JSONArray;
5 | import com.alibaba.fastjson.JSONObject;
6 |
7 |
8 | import org.loader.andnet.helper.Helper;
9 | import org.loader.andnet.net.Net;
10 | import org.loader.andnet.net.Result;
11 |
12 | import java.util.List;
13 |
14 | public class ListParser implements Net.Parser> {
15 |
16 | private String mKey;
17 |
18 | public ListParser(String key) {
19 | mKey = key;
20 | }
21 |
22 | public Result> parse(String response) {
23 | Result> result = new Result>();
24 | try {
25 | JSONObject baseObject = JSON.parseObject(response);
26 | if(!baseObject.getBooleanValue("success")) {
27 | result.setMsg(baseObject.getString("message"));
28 | }else {
29 | JSONArray arr = baseObject.getJSONArray(mKey);
30 | Class klass = Helper.generateType(getClass());
31 | List t = JSON.parseArray(arr.toJSONString(), klass);
32 | result.setStatus(Result.SUCCESS);
33 | result.setResult(t);
34 | return result;
35 | }
36 | } catch (Exception e) {
37 | e.printStackTrace();
38 | result.setMsg(Net.ERR_PARSE_MSG);
39 | }
40 |
41 | result.setStatus(Result.ERROR);
42 | return result;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/andnet/src/main/java/org/loader/andnet/helper/Helper.java:
--------------------------------------------------------------------------------
1 | package org.loader.andnet.helper;
2 |
3 | import org.loader.andnet.net.RequestParams;
4 |
5 | import java.lang.reflect.Field;
6 | import java.lang.reflect.ParameterizedType;
7 | import java.lang.reflect.Type;
8 |
9 | /**
10 | * Created by qibin on 2015/11/29.
11 | */
12 | public class Helper {
13 |
14 | public static Class generateType(Class> klass) {
15 | Type type = klass.getGenericSuperclass();
16 | if(type instanceof ParameterizedType) {
17 | ParameterizedType paramType = (ParameterizedType) type;
18 | Type[] actualTypes = paramType.getActualTypeArguments();
19 | if(actualTypes != null && actualTypes.length > 0) {
20 | return (Class) actualTypes[0];
21 | }
22 | }
23 |
24 | return null;
25 | }
26 |
27 | public static RequestParams bean2Params(IBaseBean bean) {
28 | RequestParams params = new RequestParams();
29 | Class> klass = bean.getClass();
30 | Field[] fields = klass.getDeclaredFields();
31 | for(Field f : fields) {
32 | if(!f.isAnnotationPresent(Annotation.class)) continue;
33 | Annotation annotation = f.getAnnotation(Annotation.class);
34 | String key = annotation.key();
35 | f.setAccessible(true);
36 | try {
37 | Object value = f.get(bean);
38 | if(value == null) continue;
39 | params.add(key, value);
40 | } catch (IllegalAccessException e) {
41 | e.printStackTrace();
42 | }
43 | }
44 | return params;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/andnet/src/main/java/org/loader/andnet/net/INetStack.java:
--------------------------------------------------------------------------------
1 | package org.loader.andnet.net;
2 |
3 |
4 | /**
5 | * Created by qibin on 2015/11/29.
6 | */
7 | public interface INetStack {
8 |
9 | void get(final String url, final Net.Parser parser,
10 | final Net.Callback callback, final Object tag);
11 |
12 | void post(final String url, final RequestParams params,
13 | final Net.Parser parser,
14 | final Net.Callback callback,
15 | final Object tag);
16 |
17 | void post(final String url, final String json,
18 | final Net.Parser parser,
19 | final Net.Callback callback,
20 | final Object tag);
21 |
22 | void put(final String url, final RequestParams params,
23 | final Net.Parser parser,
24 | final Net.Callback callback,
25 | final Object tag);
26 |
27 | void put(final String url, final String json,
28 | final Net.Parser parser,
29 | final Net.Callback callback,
30 | final Object tag);
31 |
32 | void delete(final String url, final Net.Parser parser,
33 | final Net.Callback callback, final Object tag);
34 |
35 | void onNetResponse(final Net.Parser parser,
36 | final Net.Callback callback,
37 | final String response);
38 |
39 | void onError(final Net.Callback callback, final String msg);
40 |
41 | void cancel(final Object tag);
42 |
43 | LinkedHashMap headers();
44 | }
45 |
--------------------------------------------------------------------------------
/samples/src/main/java/volley/VolleyManager.java:
--------------------------------------------------------------------------------
1 | package volley;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 |
6 | import com.android.volley.DefaultRetryPolicy;
7 | import com.android.volley.Request;
8 | import com.android.volley.RequestQueue;
9 | import com.android.volley.toolbox.Volley;
10 |
11 |
12 | /**
13 | * Created by qibin on 2015/11/29.
14 | */
15 | public class VolleyManager {
16 | private static VolleyManager sInstance;
17 | private RequestQueue mRequestQueue;
18 |
19 | public synchronized static VolleyManager getInstance(Application context) {
20 | if(sInstance == null) {
21 | synchronized (VolleyManager.class) {
22 | if(sInstance == null) sInstance = new VolleyManager(context.getApplicationContext());
23 | }
24 | }
25 | return sInstance;
26 | }
27 |
28 | private VolleyManager(Context context) {
29 | mRequestQueue = Volley.newRequestQueue(context);
30 | }
31 |
32 | /**
33 | * 添加一个请求
34 | * @param request
35 | */
36 | public void add(Request request) {
37 | // 重试策略
38 | request.setRetryPolicy(new DefaultRetryPolicy(5000,
39 | DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
40 | DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
41 | mRequestQueue.add(request);
42 | }
43 |
44 | /**
45 | * 添加一个请求,并设置tag
46 | * @param request
47 | * @param tag
48 | */
49 | public void add(Request request, Object tag) {
50 | if(tag != null) request.setTag(tag);
51 | add(request);
52 | }
53 |
54 | /**
55 | * 取消全部请求
56 | */
57 | public void cancelAll() {
58 | mRequestQueue.cancelAll(new RequestQueue.RequestFilter() {
59 | public boolean apply(Request> request) {
60 | return true;
61 | }
62 | });
63 | }
64 |
65 | /**
66 | * 取消指定tag的请求
67 | * @param tag
68 | */
69 | public void cancel(Object tag) {
70 | mRequestQueue.cancelAll(tag);
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/andnet/src/main/java/org/loader/andnet/net/AbsHttpStack.java:
--------------------------------------------------------------------------------
1 | package org.loader.andnet.net;
2 |
3 | /**
4 | * Created by qibin on 2015/11/29.
5 | */
6 | public abstract class AbsHttpStack implements INetStack {
7 |
8 | protected boolean debug;
9 |
10 | public void debug(boolean debug) {
11 | this.debug = debug;
12 | }
13 |
14 | public boolean isDebugMode() {
15 | return this.debug;
16 | }
17 |
18 | @Override
19 | public void post(final String url, final String json,
20 | final Net.Parser parser,
21 | final Net.Callback callback, final Object tag) {
22 | throw new UnsupportedOperationException("you must implement this operation by yourself!");
23 | }
24 |
25 | @Override
26 | public void put(final String url, final RequestParams params,
27 | final Net.Parser parser,
28 | final Net.Callback callback, final Object tag) {
29 | throw new UnsupportedOperationException("you must implement this operation by yourself!");
30 | }
31 |
32 | @Override
33 | public void put(final String url, final String json,
34 | final Net.Parser parser,
35 | final Net.Callback callback, final Object tag) {
36 | throw new UnsupportedOperationException("you must implement this operation by yourself!");
37 | }
38 |
39 | @Override
40 | public void delete(final String url, final Net.Parser parser,
41 | final Net.Callback callback, final Object tag) {
42 | throw new UnsupportedOperationException("you must implement this operation by yourself!");
43 | }
44 |
45 | /**
46 | * 请求成功
47 | *
48 | * @param parser
49 | * @param callback
50 | * @param response
51 | */
52 | @Override
53 | public void onNetResponse(final Net.Parser parser,
54 | final Net.Callback callback,
55 | final String response) {
56 | if(isDebugMode()) System.out.println(response);
57 | if (callback == null) return;
58 | if (parser == null) {
59 | Result result = new Result();
60 | result.setStatus(Result.ERROR);
61 | result.setMsg(Net.ERR_PARSE_MSG);
62 | callback.callback(result);
63 | return;
64 | }
65 |
66 | Result result = parser.parse(response);
67 | callback.callback(result);
68 | }
69 |
70 | /**
71 | * 请求失败
72 | *
73 | * @param callback
74 | * @param msg
75 | */
76 | @Override
77 | public void onError(final Net.Callback callback, final String msg) {
78 | if(isDebugMode()) System.out.println(msg);
79 | if (callback == null) return;
80 |
81 | Result result = new Result();
82 | result.setStatus(Result.ERROR);
83 | result.setMsg(msg);
84 | callback.callback(result);
85 | }
86 |
87 | @Override
88 | public LinkedHashMap headers() {
89 | return null;
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/samples/src/main/java/volley/VolleyStack.java:
--------------------------------------------------------------------------------
1 | package volley;
2 |
3 | import android.app.Application;
4 |
5 | import com.android.volley.AuthFailureError;
6 | import com.android.volley.Request;
7 | import com.android.volley.Response;
8 | import com.android.volley.VolleyError;
9 | import com.android.volley.toolbox.StringRequest;
10 |
11 |
12 | import org.loader.andnet.net.AbsHttpStack;
13 | import org.loader.andnet.net.Net;
14 | import org.loader.andnet.net.RequestParams;
15 |
16 | import java.lang.ref.WeakReference;
17 | import java.util.Map;
18 |
19 | /**
20 | * Created by qibin on 2015/11/29.
21 | */
22 | public class VolleyStack extends AbsHttpStack {
23 |
24 | private Application mContext;
25 |
26 | public VolleyStack(Application context) {
27 | mContext = context;
28 | }
29 |
30 | /**
31 | * get请求
32 | *
33 | * @param url 网址
34 | * @param parser 解析器
35 | * @param callback 回调
36 | */
37 | @Override
38 | public void get(String url, Net.Parser parser,
39 | Net.Callback callback, final Object tag) {
40 | invoke(Request.Method.GET, url, null, parser, callback, tag);
41 | }
42 |
43 | /**
44 | * post请求
45 | *
46 | * @param url 访问的url
47 | * @param params post参数
48 | * @param parser 解析器
49 | * @param callback 回调
50 | */
51 | @Override
52 | public void post(String url, RequestParams params,
53 | Net.Parser parser,
54 | Net.Callback callback,
55 | final Object tag) {
56 | invoke(Request.Method.POST, url, params, parser, callback, tag);
57 | }
58 |
59 | /**
60 | * 执行网络请求
61 | *
62 | * @param url
63 | * @param params post时请求的参数 get时为null
64 | * @param parser
65 | * @param callback
66 | * @param method
67 | */
68 | private void invoke(final int method, final String url,
69 | final RequestParams params,
70 | final Net.Parser parser,
71 | final Net.Callback callback,
72 | final Object tag) {
73 | StringRequest request = new StringRequest(method, url,
74 | new Response.Listener() {
75 | public void onResponse(String response) {
76 | onNetResponse(parser, callback, response);
77 | }
78 | }, new Response.ErrorListener() {
79 | public void onErrorResponse(VolleyError error) {
80 | error.printStackTrace();
81 | onError(callback, Net.DEF_ERR_MSG);
82 | }
83 | }) {
84 | @Override
85 | protected Map getParams()
86 | throws AuthFailureError {
87 | if (params != null) return params.get();
88 | return super.getParams();
89 | }
90 | };
91 |
92 | VolleyManager.getInstance(mContext).add(request, tag);
93 | }
94 |
95 | @Override
96 | public void cancel(Object tag) {
97 | VolleyManager.getInstance(mContext).cancel(tag);
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/samples/src/main/java/org/loader/nettest/MainActivity.java:
--------------------------------------------------------------------------------
1 | package org.loader.nettest;
2 |
3 | import android.os.Bundle;
4 | import android.os.Environment;
5 | import android.support.v7.app.AppCompatActivity;
6 | import android.widget.AdapterView;
7 | import android.widget.BaseAdapter;
8 | import android.widget.ListView;
9 | import android.widget.TextView;
10 |
11 | import org.loader.andnet.net.Net;
12 | import org.loader.andnet.net.RequestParams;
13 | import org.loader.andnet.net.Result;
14 |
15 | import java.io.File;
16 |
17 |
18 | public class MainActivity extends AppCompatActivity {
19 |
20 | private TextView mTextView;
21 |
22 | @Override
23 | protected void onCreate(Bundle savedInstanceState) {
24 | super.onCreate(savedInstanceState);
25 | setContentView(R.layout.activity_main);
26 |
27 | mTextView = (TextView) findViewById(R.id.tv);
28 |
29 | Net.get("http://192.168.3.116/?name=loader&age=18&city=jinan",
30 | new CommParser("user") {}, new Net.Callback() {
31 | @Override
32 | public void callback(Result result) {
33 | if(result.getStatus() == Result.SUCCESS) {
34 | User user = result.getResult();
35 |
36 | mTextView.setText(user.getName());
37 | mTextView.append("\n" + user.getAge());
38 | mTextView.append("\n" + user.getCity());
39 | }else {
40 | mTextView.setText(result.getMsg());
41 | }
42 | }
43 | }, getClass().getName());
44 |
45 |
46 | // RequestParams params = new RequestParams("name", "loader");
47 | // params.add("age", 18).add("city", "jinan");
48 | // Net.post("http://192.168.3.116/", params, new CommParser("user") {
49 | // },
50 | // new Net.Callback() {
51 | // @Override
52 | // public void callback(Result result) {
53 | // if(result.getStatus() == Result.SUCCESS) {
54 | // User user = result.getResult();
55 | //
56 | // mTextView.setText(user.getName());
57 | // mTextView.append("\n" + user.getAge());
58 | // mTextView.append("\n" + user.getCity());
59 | // }else {
60 | // mTextView.setText(result.getMsg());
61 | // }
62 | // }
63 | // }, getClass().getName());
64 |
65 |
66 | // User user = new User();
67 | // user.setName("qibin");
68 | // user.setCity("shandong");
69 | // user.setAge(18);
70 | //
71 | // Net.post("http://192.168.3.116/", user, new CommParser("user") {
72 | // }, new Net.Callback() {
73 | // @Override
74 | // public void callback(Result result) {
75 | // if(result.getStatus() == Result.SUCCESS) {
76 | // mTextView.setText(result.getResult().toString());
77 | // }else {
78 | // mTextView.setText(result.getMsg());
79 | // }
80 | // }
81 | // }, getClass().getName());
82 |
83 | // RequestParams params = new RequestParams("name", "qibin");
84 | // params.add("file", new File(Environment.getExternalStorageDirectory()
85 | // + "/dl.jar"));
86 | // Net.post("http://192.168.3.116/upload.php", params, new Net.NoParser(),
87 | // new Net.Callback() {
88 | // @Override
89 | // public void callback(Result result) {
90 | // mTextView.setText(result.getResult() + "");
91 | // }
92 | // }, getClass().getName());
93 | }
94 |
95 | @Override
96 | protected void onDestroy() {
97 | Net.cancel(getClass().getName());
98 | super.onDestroy();
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/andnet/src/main/java/org/loader/andnet/net/Net.java:
--------------------------------------------------------------------------------
1 | package org.loader.andnet.net;
2 |
3 | import org.loader.andnet.helper.Helper;
4 | import org.loader.andnet.helper.IBaseBean;
5 |
6 | /**
7 | * Created by qibin on 2015/11/29.
8 | */
9 | public class Net {
10 |
11 | /**
12 | * 默认错误提醒
13 | */
14 | public static final String DEF_ERR_MSG = "请求失败";
15 | /**
16 | * 数据解析失败
17 | */
18 | public static final String ERR_PARSE_MSG = "数据解析失败";
19 |
20 | private static INetStack sNetStack;
21 |
22 | public static void init(INetStack netStack) {
23 | sNetStack = netStack;
24 | }
25 |
26 | /**
27 | * get请求
28 | *
29 | * @param url 网址
30 | * @param parser 解析器
31 | * @param callback 回调
32 | */
33 | public static void get(final String url, final Parser parser,
34 | final Callback callback, final Object tag) {
35 | try {
36 | sNetStack.get(url, parser, callback, tag);
37 | } catch (Exception e) {
38 | e.printStackTrace();
39 | }
40 | }
41 |
42 | /**
43 | * post请求
44 | *
45 | * @param url 访问的url
46 | * @param params post参数
47 | * @param parser 解析器
48 | * @param callback 回调
49 | */
50 | public static void post(final String url, final RequestParams params,
51 | final Parser parser, final Callback callback, final Object tag) {
52 | try {
53 | sNetStack.post(url, params, parser, callback, tag);
54 | } catch (Exception e) {
55 | e.printStackTrace();
56 | }
57 | }
58 |
59 | /**
60 | * post请求
61 | *
62 | * @param url 访问的url
63 | * @param params post参数
64 | * @param parser 解析器
65 | * @param callback 回调
66 | */
67 | public static void post(final String url, final IBaseBean params,
68 | final Parser parser, final Callback callback,
69 | final Object tag) {
70 | try {
71 | sNetStack.post(url, Helper.bean2Params(params),
72 | parser, callback, tag);
73 | } catch (Exception e) {
74 | e.printStackTrace();
75 | }
76 | }
77 |
78 | /**
79 | * post json
80 | * @param url
81 | * @param json
82 | * @param parser
83 | * @param callback
84 | * @param tag
85 | * @param
86 | */
87 | public static void post(final String url, final String json,
88 | final Parser parser,
89 | final Callback callback, final Object tag) {
90 | try {
91 | sNetStack.post(url, json,
92 | parser, callback, tag);
93 | } catch (Exception e) {
94 | e.printStackTrace();
95 | }
96 | }
97 |
98 | /**
99 | * put请求
100 | * @param url
101 | * @param params
102 | * @param parser
103 | * @param callback
104 | * @param tag
105 | * @param
106 | */
107 | public static void put(final String url, final RequestParams params,
108 | final Parser parser,
109 | final Callback callback, final Object tag) {
110 | try {
111 | sNetStack.put(url, params, parser, callback, tag);
112 | } catch (Exception e) {
113 | e.printStackTrace();
114 | }
115 | }
116 |
117 | /**
118 | * put请求
119 | *
120 | * @param url 访问的url
121 | * @param params put参数
122 | * @param parser 解析器
123 | * @param callback 回调
124 | */
125 | public static void put(final String url, final IBaseBean params,
126 | final Parser parser, final Callback callback,
127 | final Object tag) {
128 | try {
129 | sNetStack.put(url, Helper.bean2Params(params),
130 | parser, callback, tag);
131 | } catch (Exception e) {
132 | e.printStackTrace();
133 | }
134 | }
135 |
136 | /**
137 | * put json
138 | * @param url
139 | * @param json
140 | * @param parser
141 | * @param callback
142 | * @param tag
143 | * @param
144 | */
145 | public static void put(final String url, final String json,
146 | final Parser parser,
147 | final Callback callback, final Object tag) {
148 | try {
149 | sNetStack.put(url, json, parser, callback, tag);
150 | } catch (Exception e) {
151 | e.printStackTrace();
152 | }
153 | }
154 |
155 | /**
156 | * delete请求
157 | * @param url
158 | * @param parser
159 | * @param callback
160 | * @param tag
161 | * @param
162 | */
163 | public static void delete(final String url, final Parser parser,
164 | final Callback callback, final Object tag) {
165 | try {
166 | sNetStack.delete(url, parser, callback, tag);
167 | } catch (Exception e) {
168 | e.printStackTrace();
169 | }
170 | }
171 |
172 | /**
173 | * cancel请求
174 | * @param tag
175 | */
176 | public static void cancel(final Object tag) {
177 | if(sNetStack != null) sNetStack.cancel(tag);
178 | }
179 |
180 | /**
181 | * 数据返回接口
182 | *
183 | * @param
184 | * @author loader
185 | */
186 | public interface Callback {
187 | void callback(Result result);
188 | }
189 |
190 | /**
191 | * 数据解析接口
192 | *
193 | * @param
194 | * @author loader
195 | */
196 | public interface Parser {
197 | Result parse(String response);
198 | }
199 |
200 | /**
201 | * 不做任何解析,返回原本的字符串
202 | */
203 | public static class NoParser implements Parser {
204 | public Result parse(String response) {
205 | Result res = new Result();
206 | res.setResult(response);
207 | return res;
208 | }
209 | }
210 | }
211 |
--------------------------------------------------------------------------------
/andnet/andnet.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | generateDebugAndroidTestSources
19 | generateDebugSources
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
--------------------------------------------------------------------------------
/andnet/src/main/java/org/loader/andnet/okhttp/OkHttpStack.java:
--------------------------------------------------------------------------------
1 | package org.loader.andnet.okhttp;
2 |
3 | import android.os.Handler;
4 |
5 | import com.squareup.okhttp.Call;
6 | import com.squareup.okhttp.Callback;
7 | import com.squareup.okhttp.Headers;
8 | import com.squareup.okhttp.MediaType;
9 | import com.squareup.okhttp.MultipartBuilder;
10 | import com.squareup.okhttp.OkHttpClient;
11 | import com.squareup.okhttp.Request;
12 | import com.squareup.okhttp.RequestBody;
13 | import com.squareup.okhttp.Response;
14 |
15 | import org.loader.andnet.net.AbsHttpStack;
16 | import org.loader.andnet.net.Net;
17 | import org.loader.andnet.net.RequestParams;
18 |
19 | import java.io.File;
20 | import java.io.IOException;
21 | import java.util.Iterator;
22 | import java.util.LinkedHashMap;
23 | import java.util.concurrent.TimeUnit;
24 |
25 | /**
26 | * Created by qibin on 2015/11/29.
27 | */
28 | public class OkHttpStack extends AbsHttpStack {
29 |
30 | private OkHttpClient mClient;
31 | private Handler mHandler;
32 |
33 | public OkHttpStack() {
34 | mClient = new OkHttpClient();
35 | mHandler = new Handler();
36 | }
37 |
38 | @Override
39 | public void get(final String url, final Net.Parser parser,
40 | final Net.Callback callback,
41 | final Object tag) {
42 | final Request request = new Request.Builder()
43 | .url(url).build();
44 | call(request, parser, callback, tag);
45 | }
46 |
47 | @Override
48 | public void post(final String url, final RequestParams params,
49 | final Net.Parser parser,
50 | final Net.Callback callback,
51 | final Object tag) {
52 | MultipartBuilder builder = createRequestBody(params);
53 | Request request = new Request.Builder()
54 | .url(url).post(builder.build()).build();
55 | call(request, parser, callback, tag);
56 | }
57 |
58 | @Override
59 | public void post(final String url, final String json,
60 | final Net.Parser parser,
61 | final Net.Callback callback, final Object tag) {
62 | Request request = new Request.Builder()
63 | .url(url).post(createJsonBody(json)).build();
64 | call(request, parser, callback, tag);
65 | }
66 |
67 | @Override
68 | public void put(final String url, final RequestParams params,
69 | final Net.Parser parser,
70 | final Net.Callback callback,
71 | final Object tag) {
72 | MultipartBuilder builder = createRequestBody(params);
73 | Request request = new Request.Builder()
74 | .url(url).put(builder.build()).build();
75 | call(request, parser, callback, tag);
76 | }
77 |
78 | @Override
79 | public void put(final String url, final String json,
80 | final Net.Parser parser,
81 | final Net.Callback callback, final Object tag) {
82 | Request request = new Request.Builder()
83 | .url(url).put(createJsonBody(json)).build();
84 | call(request, parser, callback, tag);
85 | }
86 |
87 | @Override
88 | public void delete(final String url, final Net.Parser parser,
89 | final Net.Callback callback,
90 | final Object tag) {
91 | final Request request = new Request.Builder()
92 | .url(url).delete().build();
93 | call(request, parser, callback, tag);
94 | }
95 |
96 | private RequestBody createJsonBody(String json) {
97 | RequestBody body = RequestBody.create(MediaType
98 | .parse("application/json;charset=utf-8"), json);
99 | return body;
100 | }
101 |
102 | private MultipartBuilder createRequestBody(RequestParams params) {
103 | MultipartBuilder builder = new MultipartBuilder()
104 | .type(MultipartBuilder.FORM);
105 |
106 | LinkedHashMap map = params.get();
107 | for(Iterator iterator=map.keySet().iterator();iterator.hasNext();) {
108 | String key = iterator.next();
109 | String value = map.get(key);
110 | if(value == null) continue;
111 | builder.addPart(Headers.of("Content-Disposition",
112 | "form-data; name=\""+ key +"\""),
113 | RequestBody.create(null, value));
114 | }
115 |
116 | LinkedHashMap files = params.files();
117 | for(Iterator iterator=files.keySet().iterator();iterator.hasNext();) {
118 | String key = iterator.next();
119 | File file = files.get(key);
120 | if(file == null) continue;
121 | builder.addPart(Headers.of("Content-Disposition",
122 | "form-data; name=\"" + key + "\";filename=\""+ file.getName() +"\""),
123 | RequestBody.create(MediaType.parse("application/octet-stream"), file));
124 | }
125 |
126 | return builder;
127 | }
128 |
129 | private void call(Request request, final Net.Parser parser,
130 | final Net.Callback callback,
131 | final Object tag) {
132 | Request.Builder builder = request.newBuilder();
133 | builder.tag(tag);
134 | LinkedHashMap map = headers();
135 | if(map != null && !map.isEmpty()) {
136 | for(Iterator iterator=map.keySet().iterator();iterator.hasNext();) {
137 | String key = iterator.next();
138 | String value = map.get(key);
139 | if(value == null) continue;
140 | builder.addHeader(key, value);
141 | }
142 | request = builder.build();
143 | }
144 |
145 | OkHttpClient client = mClient.clone();
146 | client.setConnectTimeout(20, TimeUnit.SECONDS);
147 |
148 | final Call call = client.newCall(request);
149 | call.enqueue(new Callback() {
150 | @Override
151 | public void onFailure(Request request, final IOException e) {
152 | final String msg = e.getMessage();
153 | mHandler.post(new Runnable() {
154 | @Override
155 | public void run() {
156 | onError(callback, msg);
157 | }
158 | });
159 | }
160 |
161 | @Override
162 | public void onResponse(final Response response) throws IOException {
163 | final String resp = response.body().string();
164 | mHandler.post(new Runnable() {
165 | @Override
166 | public void run() {
167 | onNetResponse(parser, callback, resp);
168 | }
169 | });
170 | }
171 | });
172 | }
173 |
174 | public LinkedHashMap headers() {
175 | // TODO add your custom headers here!
176 | return null;
177 | }
178 |
179 | @Override
180 | public void cancel(final Object tag) {
181 | mClient.cancel(tag);
182 | }
183 | }
184 |
--------------------------------------------------------------------------------
/samples/simples.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | generateDebugAndroidTestSources
19 | generateDebugSources
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## 我最新的网络框架请移步[https://github.com/qibin0506/Glin](https://github.com/qibin0506/Glin)
2 | # AndNet
3 | AndNet是一个Android开中中二次封装的网络框架,可以任意轻松切换使用的底层网络请求框架,AndNet使用Parser-Callback模式,可以轻松实现从网络请求到数据解析的整个操作步骤。
4 |
5 | AndNet的网络请求框架默认使用OkHttp,当然你完全可以轻松的实现自己的请求操作并且替换,而你的业务逻辑代码无需任何变动。
6 |
7 | ## 更新日志
8 |
9 | ### 0.1.2版本更新
10 |
11 | 1. 加入put、delete请求的支持
12 | 2. 可直接post、put一段json
13 | 3. cancel加入stack为空判断
14 |
15 | ***
16 |
17 | ### 0.1.1版本更新
18 |
19 | 1. 加入debug
20 | 2. 修复WeakReference带来的问题
21 | 3. 重用网络框架的cancel功能,加入tag标识
22 |
23 | ## 使用
24 |
25 | ### 1 初始化
26 |
27 | ``` java
28 | public class App extends Application {
29 |
30 | @Override
31 | public void onCreate() {
32 | super.onCreate();
33 | OkHttpStack okHttpStack = new OkHttpStack();
34 | okHttpStack.debug(true);
35 | Net.init(okHttpStack);
36 |
37 | }
38 | }
39 | ```
40 |
41 | ### 2 定义parser
42 |
43 | ``` java
44 | public class CommParser implements Net.Parser {
45 |
46 | private String mKey;
47 |
48 | public CommParser(String key) {
49 | mKey = key;
50 | }
51 |
52 | @Override
53 | public Result parse(String response) {
54 | Result result = new Result();
55 | try {
56 | JSONObject baseObject = JSON.parseObject(response);
57 | if(!baseObject.getBooleanValue("success")) {
58 | result.setMsg(baseObject.getString("message"));
59 | }else {
60 | Class klass = Helper.generateType(getClass());
61 | if(klass == null) throw new Exception();
62 |
63 | T t = baseObject.getObject(mKey, klass);
64 | result.setStatus(Result.SUCCESS);
65 | result.setResult(t);
66 | return result;
67 | }
68 | } catch (Exception e) {
69 | e.printStackTrace();
70 | result.setMsg(Net.ERR_PARSE_MSG);
71 | }
72 |
73 | result.setStatus(Result.ERROR);
74 | return result;
75 | }
76 | }
77 |
78 | ```
79 |
80 | ### 3 get请求
81 |
82 | ``` java
83 | Net.get("http://192.168.3.116/?name=loader&age=18&city=jinan",
84 | new CommParser("user") {}, new Net.Callback() {
85 | @Override
86 | public void callback(Result result) {
87 | if(result.getStatus() == Result.SUCCESS) {
88 | User user = result.getResult();
89 |
90 | mTextView.setText(user.getName());
91 | mTextView.append("\n" + user.getAge());
92 | mTextView.append("\n" + user.getCity());
93 | }else {
94 | mTextView.setText(result.getMsg());
95 | }
96 | }
97 | }, getClass().getName());
98 | ```
99 |
100 | ### 4 post请求
101 | ``` java
102 | User user = new User();
103 | user.setName("qibin");
104 | user.setCity("shandong");
105 | user.setAge(18);
106 |
107 | Net.post("http://192.168.3.116/", user, new CommParser("user") {
108 | }, new Net.Callback() {
109 | @Override
110 | public void callback(Result result) {
111 | if(result.getStatus() == Result.SUCCESS) {
112 | mTextView.setText(result.getResult().toString());
113 | }else {
114 | mTextView.setText(result.getMsg());
115 | }
116 | }
117 | }, getClass().getName());
118 | ```
119 |
120 | ### 5 文件上传
121 |
122 | ``` java
123 |
124 | RequestParams params = new RequestParams("name", "qibin");
125 | params.add("file", new File(Environment.getExternalStorageDirectory()
126 | + "/dl.jar"));
127 | Net.post("http://192.168.3.116/upload.php", params, new Net.NoParser(),
128 | new Net.Callback() {
129 | @Override
130 | public void callback(Result result) {
131 | mTextView.setText(result.getResult() + "");
132 | }
133 | }, getClass().getName());
134 | ```
135 |
136 | ### cancel
137 |
138 | ``` java
139 |
140 | class MyActivity extend Activity {
141 |
142 | @Override
143 | public void onDestroy() {
144 | Net.cancel(getClass().getName());
145 | }
146 | }
147 |
148 | ```
149 |
150 | ### 6 定制HttpStack
151 | ``` java
152 | public class VolleyStack extends AbsHttpStack {
153 |
154 | private Application mContext;
155 |
156 | public VolleyStack(Application context) {
157 | mContext = context;
158 | }
159 |
160 | /**
161 | * get请求
162 | *
163 | * @param url 网址
164 | * @param parser 解析器
165 | * @param callback 回调
166 | */
167 | @Override
168 | public void get(String url, Net.Parser parser,
169 | Net.Callback callback, final Object tag) {
170 | invoke(Request.Method.GET, url, null, parser, callback, tag);
171 | }
172 |
173 | /**
174 | * post请求
175 | *
176 | * @param url 访问的url
177 | * @param params post参数
178 | * @param parser 解析器
179 | * @param callback 回调
180 | */
181 | @Override
182 | public void post(String url, RequestParams params,
183 | Net.Parser parser,
184 | Net.Callback callback,
185 | final Object tag) {
186 | invoke(Request.Method.POST, url, params, parser, callback, tag);
187 | }
188 |
189 | /**
190 | * 执行网络请求
191 | *
192 | * @param url
193 | * @param params post时请求的参数 get时为null
194 | * @param parser
195 | * @param callback
196 | * @param method
197 | */
198 | private void invoke(final int method, final String url,
199 | final RequestParams params,
200 | final Net.Parser parser,
201 | final Net.Callback callback,
202 | final Object tag) {
203 | StringRequest request = new StringRequest(method, url,
204 | new Response.Listener() {
205 | public void onResponse(String response) {
206 | onNetResponse(parser, callback, response);
207 | }
208 | }, new Response.ErrorListener() {
209 | public void onErrorResponse(VolleyError error) {
210 | error.printStackTrace();
211 | onError(callback, Net.DEF_ERR_MSG);
212 | }
213 | }) {
214 | @Override
215 | protected Map getParams()
216 | throws AuthFailureError {
217 | if (params != null) return params.get();
218 | return super.getParams();
219 | }
220 | };
221 |
222 | VolleyManager.getInstance(mContext).add(request, tag);
223 | }
224 |
225 | @Override
226 | public void cancel(Object tag) {
227 | VolleyManager.getInstance(mContext).cancel(tag);
228 | }
229 | }
230 |
231 | public class App extends Application {
232 |
233 | @Override
234 | public void onCreate() {
235 | super.onCreate();
236 | Net.init(new VolleyStack(this));
237 | // Net.init(new OkHttpStack());
238 | // Net.init(new OkHttpHeaderStack());
239 | }
240 | }
241 | ```
242 |
243 | 更多内容请操作实例代码和博客:[http://blog.csdn.net/qibin0506/article/details/50127223](http://blog.csdn.net/qibin0506/article/details/50127223)
244 |
--------------------------------------------------------------------------------
/samples/nettest.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | generateDebugAndroidTestSources
19 | generateDebugSources
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------