Tecent:android端AysncHttpClient使用
HttpManager封装
1 public void sendRequest(String url, Map<String,String> headers,Map<String, String> params, 2 final ObjectCallback<Object> callback) { 3 AsyncHttpClient client = new AsyncHttpClient(); 4 5 // 请求消息头 6 if (headers != null) { 7 for (Map.Entry<String, String> me : headers.entrySet()) { 8 client.addHeader(me.getKey(), me.getValue()); 9 } 10 } 11 12 RequestParams requestParams = new RequestParams(); 13 if (params != null) { 14 for (Map.Entry<String, String> map : params.entrySet()) { 15 requestParams.put(map.getKey(), map.getValue()); 16 } 17 } 18 19 client.post(context, url, requestParams, new TextHttpResponseHandler() { 20 21 @Override 22 public void onSuccess(int statusCode, Header[] headers, 23 String responseString) { 24 // 25 JsonParser parser = new JsonParser(); 26 JsonElement element = parser.parse(responseString); 27 JsonObject root = element.getAsJsonObject(); 28 JsonPrimitive jsonFlag = root.getAsJsonPrimitive("flag"); 29 boolean flag = jsonFlag.getAsBoolean(); 30 31 if (flag) { 32 JsonObject dataObject = root.getAsJsonObject("data"); 33 if (dataObject != null) { 34 if (callback != null) { 35 @SuppressWarnings("unchecked") 36 Object object = new Gson().fromJson(dataObject, 37 callback.getDataClass()); 38 callback.onSuccess(object); 39 40 } 41 } 42 43 } else { 44 JsonPrimitive errorCodeJson = root 45 .getAsJsonPrimitive("errorCode"); 46 JsonPrimitive errorStringJson = root 47 .getAsJsonPrimitive("errorString"); 48 49 Log.d("", errorCodeJson.getAsInt() + " : " 50 + errorStringJson.getAsString()); 51 52 if (callback != null) { 53 callback.onFailure(errorCodeJson.getAsInt(), 54 errorStringJson.getAsString()); 55 } 56 } 57 58 } 59 60 @Override 61 public void onFailure(int statusCode, Header[] headers, 62 String responseString, Throwable throwable) { 63 Log.d("error", responseString + " : " + throwable.getMessage()); 64 65 if (callback != null) { 66 callback.onFailure(HMError.ERROR_SERVER, "服务器连接问题"); 67 } 68 69 } 70 }); 71 72 }
ObjectCallback
1 public abstract class ObjectCallback<T> { 2 3 private final Class<T> clazz; 4 5 @SuppressWarnings("unchecked") 6 public ObjectCallback() { 7 ParameterizedType type = (ParameterizedType) this.getClass() 8 .getGenericSuperclass(); 9 clazz = (Class<T>) type.getActualTypeArguments()[0]; 10 } 11 12 public Class<T> getDataClass() { 13 return clazz; 14 } 15 16 public abstract void onSuccess(T data); 17 18 public abstract void onFailure(int errorCode, String errorString); 19 }