PageRenderTime 47ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/src/main/java/com/lean56/andplug/network/FastJsonHttpResponseHandler.java

https://gitlab.com/chgocn/AndPlug
Java | 237 lines | 136 code | 19 blank | 82 comment | 28 complexity | 52ddc406100c0bb85914287ca0809e9b MD5 | raw file
Possible License(s): Apache-2.0
  1. package com.lean56.andplug.network;
  2. import android.util.Log;
  3. import com.alibaba.fastjson.JSON;
  4. import com.alibaba.fastjson.JSONArray;
  5. import com.alibaba.fastjson.JSONException;
  6. import com.alibaba.fastjson.JSONObject;
  7. import com.loopj.android.http.AsyncHttpClient;
  8. import com.loopj.android.http.TextHttpResponseHandler;
  9. import org.apache.http.Header;
  10. import org.apache.http.HttpStatus;
  11. /**
  12. * Used to intercept and handle the responses from requests made using {@link AsyncHttpClient},
  13. * with automatic parsing into a {@link JSONObject} or {@link JSONArray}.
  14. * This class is designed to be passed to get, post, put and delete requests with the
  15. * {@link #onSuccess(int,Header[], JSONArray)}
  16. * or {@link #onSuccess(int,Header[], JSONObject)}
  17. * methods anonymously overridden.
  18. *
  19. * Additionally, you can override the other event methods from the parent class.
  20. *
  21. * @author Charles <zhangchaoxu@gmail.com>
  22. */
  23. public class FastJsonHttpResponseHandler extends TextHttpResponseHandler {
  24. private static final String LOG_TAG = FastJsonHttpResponseHandler.class.getSimpleName();
  25. /**
  26. * Creates new FastJsonHttpResponseHandler, with JSON String encoding UTF-8
  27. */
  28. public FastJsonHttpResponseHandler() {
  29. super(DEFAULT_CHARSET);
  30. }
  31. /**
  32. * Creates new FastJsonHttpResponseHandler with given JSON String encoding
  33. *
  34. * @param encoding String encoding to be used when parsing JSON
  35. */
  36. public FastJsonHttpResponseHandler(String encoding) {
  37. super(encoding);
  38. }
  39. @Override
  40. public void onSuccess(int statusCode, Header[] headers, String responseString) {
  41. onFailure(statusCode, headers, (String) responseString, new JSONException("Response cannot be parsed as JSON data"));
  42. }
  43. /**
  44. * Returns when request succeeds
  45. *
  46. * @param statusCode
  47. * http response status line
  48. * @param headers
  49. * response headers if any
  50. * @param response
  51. * parsed response if any
  52. */
  53. public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
  54. }
  55. /**
  56. * Returns when request succeeds
  57. *
  58. * @param statusCode
  59. * http response status line
  60. * @param headers
  61. * response headers if any
  62. * @param response
  63. * parsed response if any
  64. */
  65. public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
  66. onFailure(statusCode, headers, response, new JSONException("JSONArray is not expected response type"));
  67. }
  68. @Override
  69. public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
  70. onFailure(statusCode, headers, (JSONObject) null, throwable);
  71. }
  72. /**
  73. * Returns when request failed
  74. *
  75. * @param statusCode
  76. * http response status line
  77. * @param headers
  78. * response headers if any
  79. * @param throwable
  80. * throwable describing the way request failed
  81. * @param errorResponse
  82. * parsed response if any
  83. */
  84. public void onFailure(int statusCode, Header[] headers, JSONObject errorResponse, Throwable throwable) {
  85. }
  86. /**
  87. * Returns when request failed
  88. *
  89. * @param statusCode
  90. * http response status line
  91. * @param headers
  92. * response headers if any
  93. * @param throwable
  94. * throwable describing the way request failed
  95. * @param errorResponse
  96. * parsed response if any
  97. */
  98. public void onFailure(int statusCode, Header[] headers, JSONArray errorResponse, Throwable throwable) {
  99. onFailure(statusCode, headers, (JSONObject) null, throwable);
  100. }
  101. @Override
  102. public final void onSuccess(final int statusCode, final Header[] headers, final byte[] responseBytes) {
  103. if (statusCode != HttpStatus.SC_NO_CONTENT) {
  104. Runnable parser = new Runnable() {
  105. @Override
  106. public void run() {
  107. try {
  108. final Object jsonResponse = parseResponse(responseBytes);
  109. postRunnable(new Runnable() {
  110. @Override
  111. public void run() {
  112. if (jsonResponse instanceof JSONObject) {
  113. onSuccess(statusCode, headers, (JSONObject) jsonResponse);
  114. } else if (jsonResponse instanceof JSONArray) {
  115. onSuccess(statusCode, headers, (JSONArray) jsonResponse);
  116. } else if (jsonResponse instanceof String) {
  117. onSuccess(statusCode, headers, (String) jsonResponse);
  118. } else {
  119. onFailure(statusCode, headers, (JSONObject) null, new JSONException("Unexpected response type "
  120. + jsonResponse.getClass().getName()));
  121. }
  122. }
  123. });
  124. } catch (final JSONException ex) {
  125. postRunnable(new Runnable() {
  126. @Override
  127. public void run() {
  128. onFailure(statusCode, headers, (JSONObject) null, ex);
  129. }
  130. });
  131. }
  132. }
  133. };
  134. if (!getUseSynchronousMode())
  135. new Thread(parser).start();
  136. else
  137. // In synchronous mode everything should be run on one thread
  138. parser.run();
  139. } else {
  140. onSuccess(statusCode, headers, new JSONObject());
  141. }
  142. }
  143. @Override
  144. public final void onFailure(final int statusCode, final Header[] headers, final byte[] responseBytes, final Throwable throwable) {
  145. if (responseBytes != null) {
  146. Runnable parser = new Runnable() {
  147. @Override
  148. public void run() {
  149. try {
  150. final Object jsonResponse = parseResponse(responseBytes);
  151. postRunnable(new Runnable() {
  152. @Override
  153. public void run() {
  154. if (jsonResponse instanceof JSONObject) {
  155. onFailure(statusCode, headers, (JSONObject) jsonResponse, throwable);
  156. } else if (jsonResponse instanceof JSONArray) {
  157. onFailure(statusCode, headers, (JSONArray) jsonResponse, throwable);
  158. } else if (jsonResponse instanceof String) {
  159. onFailure(statusCode, headers, (String) jsonResponse, throwable);
  160. } else {
  161. onFailure(statusCode, headers, (JSONObject) null, new JSONException("Unexpected response type "
  162. + jsonResponse.getClass().getName()));
  163. }
  164. }
  165. });
  166. } catch (final JSONException ex) {
  167. postRunnable(new Runnable() {
  168. @Override
  169. public void run() {
  170. onFailure(statusCode, headers, (JSONObject) null, ex);
  171. }
  172. });
  173. }
  174. }
  175. };
  176. if (!getUseSynchronousMode())
  177. new Thread(parser).start();
  178. else
  179. // In synchronous mode everything should be run on one thread
  180. parser.run();
  181. } else {
  182. Log.v(LOG_TAG, "response body is null, calling onFailure(Throwable, JSONObject)");
  183. onFailure(statusCode, headers, (JSONObject) null, throwable);
  184. }
  185. }
  186. /**
  187. * Returns Object of type {@link JSONObject}, {@link JSONArray}, String,
  188. * Boolean, Integer, Long, Double or {@link JSONObject}, see
  189. * {@link org.json.JSONTokener#nextValue()}
  190. *
  191. * @param responseBody
  192. * response bytes to be assembled in String and parsed as JSON
  193. * @return Object
  194. * parsedResponse
  195. * @throws JSONException
  196. * exception if thrown while parsing JSON
  197. */
  198. protected Object parseResponse(byte[] responseBody) throws JSONException {
  199. if (null == responseBody)
  200. return null;
  201. Object result = null;
  202. // trim the string to prevent start with blank, and test if the string
  203. // is valid JSON, because the parser don't do this :(. If JSON is not
  204. // valid this will return null
  205. String jsonString = getResponseString(responseBody, getCharset());
  206. if (jsonString != null) {
  207. jsonString = jsonString.trim();
  208. if (jsonString.startsWith("{") || jsonString.startsWith("[")) {
  209. // result = new JSONTokener(jsonString).nextValue();
  210. result = JSON.parse(jsonString);
  211. }
  212. }
  213. if (result == null) {
  214. result = jsonString;
  215. }
  216. return result;
  217. }
  218. }