首页 > 代码库 > android AsyncHttpClient 开源框架的使用
android AsyncHttpClient 开源框架的使用
AsyncHttpClient
1.在很多时候android都需要进行网络的操作,而android自带的HttpClient可以实现,但要进行很多网络连接的时候(如:下载很多图片),就需要线程池来进行管理,但默认都是阻塞式操作。这种模型效率不高,对并发要求高的 APP 来讲,并不适用,要用AsyncHttpClient 就必须下载一个jar包 ------>> 下载地址。
2.AsyncHttpClient框架是异步的框架,而且已经封装好了了线程池的操作。所以对网络的操作都是很快的!
3.在AsyncHttpClient框架中主要的类如下:
主要用到的类有AsyncHttpClient , JsonHttpResponseHandler , RequestParams,
3.请求的方法:
AsyncHttpClient.post(arg0,arg1,arg2);
arg0:是你post请求的url
arg1:是要发送给服务器的数据 ,他是<key,value>形式的
arg2:发送请求的一连串操作 如下:
JsonHttpResponseHandler是AsyncHttpResponseHandler的子类
1 JsonHttpResponseHandler handler = new JsonHttpResponseHandler() { 2 @Override 3 public void onFailure(Throwable arg0, String arg1) { 4 5 super.onFailure(arg0, arg1); 6 7 } 8 9 @Override 10 public void onFinish() { 11 12 super.onFinish(); 13 14 } 15 16 @Override 17 public void onSuccess(JSONObject arg1) { 18 super.onSuccess(arg1); 19 20 } 21 22 @Override 23 public void onStart() { 24 25 super.onStart(); 26 27 } 28 };
1)onStart() 方法是开始发送请求的时候执行的,一般是把progressDialog放在这里面显示,提示用户等待
2)onFailure() 如果请求失败了,就会执行该方法,其余方法就都不执行了,用于提示用户网络出现故障
3)onSuccess() 是请求成功后,服务器就会返回JSONObject, arg1就是返回的JSONObject, 在里面解析JSONObject来回去数据,并显示在UI上
4)onFinish() 当发送请求成功后,就执行onFinish()
如上就是一些基本的用法。
这里贴一个结合AsyncHttpClient + 单例模式 + 观察者模式的例子
接口:
public interface TaskListener { public abstract void start(); public abstract String contentype(); // text, file public abstract String filepath(); public abstract String requestUrl(); public abstract JSONObject requestData(); public abstract void messageUpdated(JSONObject msg); public abstract void failure(String str); public abstract void finish(); public abstract boolean needCacheTask(); public abstract String readCache(); public abstract void updateCacheDate(List<HashMap<String, Object>> cacheData); }
实现:
19 20 public class CommandBase { 21 22 private static CommandBase m_instance = null; 23 24 private HashMap<AsyncHttpResponseHandler, TaskListener> m_task = new HashMap<AsyncHttpResponseHandler, TaskListener>(); 25 26 private AsyncHttpClient m_httpClient = new AsyncHttpClient(); 27 28 private UploadQueue m_uploadQueue = null; 29 private HashMap<AsyncHttpResponseHandler, UploadItem> m_tempRequest = new HashMap<AsyncHttpResponseHandler, UploadItem>(); 30 31 private static String m_account = ""; 32 private static String m_session = ""; 33 34 private static String HostUrl = "http://222.18.162.187:8080/wasp/webservice/ap/"; 35 private static JSONObject m_postData = http://www.mamicode.com/new JSONObject(); 36 37 Context m_context; 38 Context m_currContext; 39 Activity m_currActivity; 40 41 public void setCurrActivityContext(Context context, Activity activity) { 42 m_currContext = context; 43 m_currActivity = activity; 44 } 45 46 public void setMainActivityContext(Context context) { 47 m_context = context; 48 49 if (m_uploadQueue == null) 50 m_uploadQueue = new UploadQueue(m_context); 51 } 52 53 public static CommandBase instance() { 54 if (m_instance == null) 55 m_instance = new CommandBase(); 56 57 return m_instance; 58 } 59 60 private CommandBase() { 61 m_httpClient.addHeader("Content-Type", "application/json"); 62 m_httpClient.addHeader("Request-Client", "mobile/1.0.0"); 63 64 /* 65 * JSONObject userData = http://www.mamicode.com/new JSONObject(); try { userData.put("account", 66 * m_account); userData.put("session", m_session); 67 * m_postData.put("user", userData); } catch (JSONException e) { 68 * e.printStackTrace(); } 69 */ 70 } 71 72 public void setUserInfo(String name, String session) { 73 m_account = name; 74 m_session = session; 75 System.out.println("setUser"); 76 System.out.println("account=" + m_account); 77 JSONObject userData = http://www.mamicode.com/new JSONObject(); 78 try { 79 userData.put("account", m_account); 80 userData.put("session", m_session); 81 m_postData.put("user", userData); 82 } catch (JSONException e) { 83 e.printStackTrace(); 84 } 85 } 86 87 CacheManager manager = new CacheManager(); 88 89 public void readCache(final TaskListener taskListener) { 90 List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>(); 91 String queryStr = taskListener.readCache(); 92 list = manager.getCacheData(queryStr); 93 taskListener.updateCacheDate(list); 94 request(taskListener); 95 } 96 97 public void request(final TaskListener task) { 98 RequestParams postParam = new RequestParams(); 99 postParam.put("req", requestData(task.requestData())); 100 101 JsonHttpResponseHandler handler = new JsonHttpResponseHandler() { 102 @Override 103 public void onFailure(Throwable arg0, String arg1) { 104 task.failure(arg1); 105 super.onFailure(arg0, arg1); 106 System.out.println("网络连接失败.."); 107 if (task.needCacheTask() && m_uploadQueue != null 108 && m_tempRequest.containsKey(this)) 109 m_uploadQueue.addItemToQueue(m_tempRequest.get(this)); 110 m_tempRequest.remove(this); 111 Toast.makeText(m_currContext, "网络连接失败", Toast.LENGTH_SHORT) 112 .show(); 113 } 114 115 @Override 116 public void onFinish() { 117 task.finish(); 118 super.onFinish(); 119 System.out.println("请求结束"); 120 } 121 122 @Override 123 public void onSuccess(JSONObject arg1) { 124 super.onSuccess(arg1); 125 System.out.println("连接服务器成功!"); 126 System.out.println("结果=" + arg1); 127 readData(arg1, this); 128 } 129 130 @Override 131 public void onStart() { 132 task.start(); 133 super.onStart(); 134 System.out.println("请求开始"); 135 } 136 }; 137 138 // TODO: save network request to local DB 139 if (task.needCacheTask()) { 140 System.out.println("++++++++++++++++++++++++++++++++++++++++"); 141 m_tempRequest.put( 142 handler, 143 new UploadItem(0, requestUrl(task.requestUrl()), 144 requestData(task.requestData()), 145 task.contentype() == "text" ? 0 : 1, task 146 .filepath())); 147 148 } 149 150 m_task.put(handler, task); 151 m_httpClient.post(requestUrl(task.requestUrl()), postParam, handler); 152 153 154 155 } 156 157 private String requestUrl(String ap) { 158 return HostUrl + ap + ".action"; 159 } 160 161 private String requestData(JSONObject data) { 162 JSONObject postData = http://www.mamicode.com/new JSONObject(); 163 postData =http://www.mamicode.com/ m_postData; 164 try { 165 postData.put("data", data); 166 } catch (JSONException e) { 167 e.printStackTrace(); 168 } 169 System.out.println("postData="http://www.mamicode.com/+ postData); 170 return postData.toString(); 171 } 172 173 private void readData(JSONObject data, AsyncHttpResponseHandler handler) { 174 TaskListener task = m_task.get(handler); 175 176 if (task == null) { 177 m_task.remove(handler); 178 m_tempRequest.remove(handler); 179 return; 180 } 181 // TODO: Check the response data has Error or not 182 try { 183 JSONObject object = data.getJSONObject("error"); 184 String code = object.getString("code"); 185 String errorTag = object.getString("string"); 186 System.out.println("code=" + code); 187 System.out.println("error=" + errorTag); 188 if (code.equals("0")) { 189 object = data.getJSONObject("data"); 190 task.messageUpdated(data); 191 manager.updateCacheData(data); 192 m_tempRequest.remove(handler); 193 } else if (code.equals("-99")) { 194 Toast.makeText(m_currContext, "用户信息已过期,请重新登陆", 195 Toast.LENGTH_SHORT).show(); 196 m_currActivity.finish(); 197 } else { 198 System.out.println("#####################"); 199 if (task.needCacheTask() && m_uploadQueue != null 200 && m_tempRequest.containsKey(handler)) { 201 System.out.println("_____________________________"); 202 m_uploadQueue.addItemToQueue(m_tempRequest.get(handler)); 203 } 204 m_tempRequest.remove(handler); 205 Toast.makeText(m_currContext, errorTag, Toast.LENGTH_SHORT) 206 .show(); 207 } 208 } catch (JSONException e) { 209 e.printStackTrace(); 210 if (task.needCacheTask() && m_uploadQueue != null 211 && m_tempRequest.containsKey(handler)) { 212 m_uploadQueue.addItemToQueue(m_tempRequest.get(handler)); 213 } 214 m_tempRequest.remove(handler); 215 216 } 217 218 219 m_task.remove(handler); 220 } 221 222 }