AsyncHttp+gson解析

网上其实也有很多类似的这种框架  不过还是觉得自己写的用着比较方便,(ps:自己的总是最好的 ^_^)

闲下来整理出来了自己之前用过的框架 拿出来封装了一下。也写个记录,省的以后忘了。

本框架利用的是Async-Http.jar+gson.jar进行二次封装。

 

首先 先建立一个抽象类,并定义一些常用的抽象方法:

 1 public abstract class HttpRequest {
 2 
 3     /**
 4      * @description: 获取参数
 5      * @author:hc
 6      * @return:RequestParams
 7      * @return
 8      */
 9 
10     public abstract RequestParams getParams();
11 
12     /**
13      * @description:
14      * @author:hc
15      * @return:String
16      * @return
17      */
18 
19     public abstract String getUrlString();
20 
21     /**
22      * @description:
23      * @author:hc
24      * @return:void
25      * @param arg3
26      */
27 
28     public abstract void onFailure(Throwable arg3);
29 
30     /**
31      * @description:
32      * @author:hc
33      * @return:void
34      * @param arg2
35      */
36 
37     public abstract void onSuccess(String result);
38 }

 

然后定义网络访问成功和失败的接口:

1 public interface HttpSuccess<T> {
2 
3     public void onSuccess(T result);
4 
5 }
public interface HttpError {
    
     public void onError(Throwable arg0) ;

}

 

接下来定义一个泛型类来接收服务器返回的数据:

public class HttpData<T> {

    /**
     * @param cls
     * @param param
     * @param httpSuccess
     * @param httpError
     * @return
     */
    public HttpClassRequest<T> newHttpRequest(Class<T> cls, HashMap<String, String> param, HttpSuccess<T> httpSuccess, HttpError httpError) {

        // 如果这里请求需要添加公共参数在此添加
        // param.put(key, value)

        return new HttpClassRequest<T>(cls, param, httpSuccess, httpError);

    }
}

然后是请求数据处理类:

  1 public class HttpClassRequest<T> extends HttpRequest {
  2 
  3     private HashMap<String, String> params;
  4     private HttpError error;
  5 
  6     private HttpSuccess<T> success;
  7 
  8     private Class<T> cls;
  9 
 10     /**
 11      * create a instance HttpRequest.
 12      * 
 13      * @param cls
 14      * @param map
 15      * @param httpSuccess
 16      * @param httpError
 17      */
 18     public HttpClassRequest(Class<T> cls, HashMap<String, String> map, HttpSuccess<T> httpSuccess, HttpError httpError) {
 19         this.cls = cls;
 20         this.params = map;
 21         this.success = httpSuccess;
 22         this.error = httpError;
 23 
 24     }
 25 
 26     /**
 27      * @description: 获取参数
 28      * @author:hc
 29      * @return:RequestParams
 30      * @return
 31      */
 32 
 33     @Override
 34     public RequestParams getParams() {
 35         // TODO Auto-generated method stub
 36         final RequestParams requestParams = new RequestParams();
 37 
 38         StringBuilder stringBuilder = new StringBuilder();
 39         Iterator<String> iterator = params.keySet().iterator();
 40 
 41         while (iterator.hasNext()) {
 42 
 43             String key = iterator.next().toString();
 44 
 45             requestParams.put(key, params.get(key));
 46 
 47             String val = params.get(key);
 48             stringBuilder.append("&" + key + "=" + val);
 49 
 50         }
 51 
 52         CustomLog.d("提交参数为   %s", "=" + stringBuilder.toString());
 53 
 54         return requestParams;
 55     }
 56 
 57     /**
 58      * @description:
 59      * @author:hc
 60      * @return:String
 61      * @return
 62      */
 63 
 64     @Override
 65     public String getUrlString() {
 66         return Constant.url;
 67     }
 68 
 69     /**
 70      * @description:
 71      * @author:hc
 72      * @return:void
 73      * @param arg3
 74      */
 75 
 76     @Override
 77     public void onFailure(Throwable arg3) {
 78         if (error != null)
 79             error.onError(arg3);
 80     }
 81 
 82     /**
 83      * @description:
 84      * @author:hc
 85      * @return:void
 86      * @param arg2
 87      */
 88 
 89     @Override
 90     public void onSuccess(String arg2) {
 91 
 92         Gson gson = new Gson();
 93 
 94         CustomLog.d("结果是=%s", arg2);
 95 
 96         try {
 97             if (success != null)
 98                 success.onSuccess(gson.fromJson(arg2, cls));
 99         } catch (JsonSyntaxException e) {
100 
101             if (error != null)
102                 error.onError(e);
103         }
104 
105     }
106 }

类中的方法是由抽象类中继承下来的方法:分别是 getParams() 对请求参数进行封装;getUrlString() 返回请求连接;onFailure(Throwable throwable) 请求失败处理;onSuccess(String result) 请求成功的处理,其中 在返回成功的时候拿到返回数据,并把他封装成json对象数据回调出去。

接下来就是重点了:

 

  1 public class HttpRequestQueque {
  2 
  3     private AsyncHttpClient client;// 实例话对象
  4 
  5     private HttpRequest _httpRequst;
  6 
  7     private RequestParams params;
  8 
  9     /**
 10      * create a instance HttpRequestQueque.
 11      * 
 12      * @param context
 13      */
 14     public HttpRequestQueque(Context context) {
 15         client = new AsyncHttpClient();
 16         client.setTimeout(30000);
 17     }
 18 
 19     /**
 20      * @description: 添加请求
 21      * @author:hc
 22      * @return:void
 23      * @param httpRequst
 24      */
 25 
 26     public void add(HttpRequest httpRequst) {
 27         this._httpRequst = httpRequst;
 28         this.cance();
 29         params = httpRequst.getParams();
 30 
 31         CustomLog.d("JSONObject=%s", _httpRequst.getUrlString());
 32 
 33         this._get(_httpRequst.getUrlString(), params, new TextHttpResponseHandler() {
 34 
 35             @Override
 36             public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
 37 
 38                 CustomLog.d("http_stats_code=%s", " " + arg0);
 39 
 40                 _httpRequst.onFailure(arg3);
 41 
 42             }
 43 
 44             @Override
 45             public void onSuccess(int arg0, Header[] arg1, String arg2) {
 46                 // TODO Auto-generated method stub
 47                 _httpRequst.onSuccess(arg2);
 48             }
 49         });
 50 
 51     }
 52 
 53     /**
 54      * @description: post 上传
 55      * @author:hc
 56      * @return:void
 57      * @param httpRequst
 58      */
 59 
 60     public void addPost(HttpRequest httpRequst) {
 61 
 62         this._httpRequst = httpRequst;
 63 
 64         params = httpRequst.getParams();
 65 
 66         CustomLog.d("SERVER_URL_POST==%s", _httpRequst.getUrlString());
 67 
 68         this._post(_httpRequst.getUrlString(), params, new AsyncHttpResponseHandler() {
 69 
 70             @Override
 71             public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
 72                 _httpRequst.onSuccess(new String(responseBody));
 73 
 74             }
 75 
 76             @Override
 77             public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
 78 
 79                 CustomLog.d("statusCode ==== %d", statusCode);
 80                 _httpRequst.onFailure(error);
 81 
 82             }
 83         });
 84 
 85     }
 86 
 87     /**
 88      * @description: 取消加载
 89      * @author:hc
 90      * @return:void
 91      */
 92 
 93     public void cance() {
 94         client.cancelAllRequests(true);
 95     }
 96 
 97     /**
 98      * @description: 執行http请求
 99      * @author:hc
100      * @return:void
101      * @param urlString
102      * @param params
103      * @param res
104      */
105 
106     private void _get(String urlString, RequestParams params, AsyncHttpResponseHandler res) // url里面带参数
107     {
108         client.get(urlString, params, res);
109     }
110 
111     /**
112      * @description: 执行post请求
113      * @author:hc
114      * @return:void
115      * @param urlString
116      * @param params
117      * @param res
118      */
119 
120     private void _post(String urlString, RequestParams params, AsyncHttpResponseHandler res) // url里面带参数
121     {
122 
123         client.post(urlString, params, res);
124     }
125 }

 

之前的代码都是为了使用方便进行二次封装,最终使用的是在这里使用async-http.jar进行网络访问,然后回调我们写的方法,让我们更加快捷的拿到结果。

 

 

好了  接下来要看怎么去使用了

首先我们需要根据后台给出的接口定义我们的javabean;

javabean需要对应着后台返回的json对象来建立:如返回的json是

System_id:xxxxx 

items:[

  obj:xxxx

   ]

  }

这样我们就需要建立两个javabean,javabean的成员变量的名字必须要与json节点的名字相同,否则gson无法解析。

 

 1 public class JsonObj {
 2 
 3     String System_id;
 4     ArrayList<Itemobj> items;
 5 
 6     public String getSystem_id() {
 7         return System_id;
 8     }
 9 
10     public void setSystem_id(String system_id) {
11         System_id = system_id;
12     }
13 
14     public ArrayList<itemObj> getItems() {
15         return items;
16     }
17 
18     public void setItems(ArrayList<itemObj> items) {
19         this.items = items;
20     }
21 }

 

1 public class Itemobj{
2  String obj
3 
4 private get……
5 private set……
6    
7 }

然后则开始使用我们的框架进行网络访问了,代码如下:

先建立一个网络访问的方法:

 1 public class JsonTextData {
 2 
 3     /**
 4      * 
 5      * getFindList: 请求同时获取返回obj
 6      * TODO(这里描述这个方法适用条件 – 可选)
 7      * TODO(这里描述这个方法的执行流程 – 可选)
 8      * TODO(这里描述这个方法的使用方法 – 可选)
 9      * TODO(这里描述这个方法的注意事项 – 可选)
10      *
11      * @param  @param type
12      * @param  @param typeId
13      * @param  @param page
14      * @param  @param friendId
15      * @param  @param httpSuccess
16      * @param  @param httpError
17      * @param  @return    设定文件
18      * @return HttpClassRequest<JsonObj>    DOM对象
19      * @throws 
20      * @since  CodingExample Ver 1.1
21      */
22     public static HttpClassRequest<JsonObj> getTestObj(String page,
23             HttpSuccess<JsonObj> httpSuccess, HttpError httpError) {
24         HashMap<String, String> hashMap = new HashMap<String, String>();
25 
26         hashMap.put("r", "DiscoveryContent/list");
27         hashMap.put("pageSize", "10");
28         hashMap.put("page", page);
29 
30 
31         HttpData<JsonObj> huiHenDuoData = new HttpData<JsonObj>();
32         return huiHenDuoData.newHttpRequest(JsonObj.class, hashMap, httpSuccess, httpError);
33 
34     }
35

 

然后在我们在请求网络数据的地方使用:

public class MainActivity extends Activity {
    
    private HttpRequestQueque requestQueque; 
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        requestQueque = new HttpRequestQueque(MainActivity.this);
        
        requestQueque.add(JsonTextData.getTestObj("1", new HttpSuccess<JsonObj>() {
            
            @Override
            public void onSuccess(JsonObj jsonObj) {
                
                String obj = jsonObj.getSystem_id();
                
            }
        }, new HttpError() {
            
            @Override
            public void onError(Throwable arg0) {
                
                // TODO Auto-generated method stub
                Toast.makeText(MainActivity.this, "失败了!!!!!", 1).show();
                
            }
        }));
        }
}    

这样我们就能够轻而易举的拿到服务器给返回的数据了。

大功告成!

另附上源码地址:

有兴趣的同学可以下载下来看看  ^_^!!

http://pan.baidu.com/s/1qW9k4Kc

框架中还加入了一个上拉刷新和下拉加载的自定义listview 不同的同学可以删除掉,结构很清楚。另外还希望大神们继续封装这个框架  令他成为一个更加方便的框架。

发挥开源精神 共享成果 分享喜悦!!

 

posted @ 2015-07-15 11:33  蛋蛋嘚忧伤  阅读(895)  评论(0编辑  收藏  举报