Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

CordovaHttpBase.java 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package com.silkimen.cordovahttp;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.InputStream;
  5. import java.io.IOException;
  6. import java.net.SocketTimeoutException;
  7. import java.net.UnknownHostException;
  8. import java.nio.ByteBuffer;
  9. import javax.net.ssl.SSLException;
  10. import com.silkimen.http.HttpBodyDecoder;
  11. import com.silkimen.http.HttpRequest;
  12. import com.silkimen.http.HttpRequest.HttpRequestException;
  13. import com.silkimen.http.JsonUtils;
  14. import com.silkimen.http.TLSConfiguration;
  15. import org.apache.cordova.CallbackContext;
  16. import org.json.JSONArray;
  17. import org.json.JSONException;
  18. import org.json.JSONObject;
  19. import android.util.Base64;
  20. import android.util.Log;
  21. abstract class CordovaHttpBase implements Runnable {
  22. protected static final String TAG = "Cordova-Plugin-HTTP";
  23. protected String method;
  24. protected String url;
  25. protected String serializer = "none";
  26. protected String responseType;
  27. protected Object data;
  28. protected JSONObject headers;
  29. protected int timeout;
  30. protected boolean followRedirects;
  31. protected TLSConfiguration tlsConfiguration;
  32. protected CallbackContext callbackContext;
  33. public CordovaHttpBase(String method, String url, String serializer, Object data, JSONObject headers, int timeout,
  34. boolean followRedirects, String responseType, TLSConfiguration tlsConfiguration,
  35. CallbackContext callbackContext) {
  36. this.method = method;
  37. this.url = url;
  38. this.serializer = serializer;
  39. this.data = data;
  40. this.headers = headers;
  41. this.timeout = timeout;
  42. this.followRedirects = followRedirects;
  43. this.responseType = responseType;
  44. this.tlsConfiguration = tlsConfiguration;
  45. this.callbackContext = callbackContext;
  46. }
  47. public CordovaHttpBase(String method, String url, JSONObject headers, int timeout, boolean followRedirects,
  48. String responseType, TLSConfiguration tlsConfiguration, CallbackContext callbackContext) {
  49. this.method = method;
  50. this.url = url;
  51. this.headers = headers;
  52. this.timeout = timeout;
  53. this.followRedirects = followRedirects;
  54. this.responseType = responseType;
  55. this.tlsConfiguration = tlsConfiguration;
  56. this.callbackContext = callbackContext;
  57. }
  58. @Override
  59. public void run() {
  60. CordovaHttpResponse response = new CordovaHttpResponse();
  61. try {
  62. HttpRequest request = this.createRequest();
  63. this.prepareRequest(request);
  64. this.sendBody(request);
  65. this.processResponse(request, response);
  66. request.disconnect();
  67. } catch (HttpRequestException e) {
  68. if (e.getCause() instanceof SSLException) {
  69. response.setStatus(-2);
  70. response.setErrorMessage("TLS connection could not be established: " + e.getMessage());
  71. Log.w(TAG, "TLS connection could not be established", e);
  72. } else if (e.getCause() instanceof UnknownHostException) {
  73. response.setStatus(-3);
  74. response.setErrorMessage("Host could not be resolved: " + e.getMessage());
  75. Log.w(TAG, "Host could not be resolved", e);
  76. } else if (e.getCause() instanceof SocketTimeoutException) {
  77. response.setStatus(-4);
  78. response.setErrorMessage("Request timed out: " + e.getMessage());
  79. Log.w(TAG, "Request timed out", e);
  80. } else {
  81. response.setStatus(-1);
  82. response.setErrorMessage("There was an error with the request: " + e.getCause().getMessage());
  83. Log.w(TAG, "Generic request error", e);
  84. }
  85. } catch (Exception e) {
  86. response.setStatus(-1);
  87. response.setErrorMessage(e.getMessage());
  88. Log.e(TAG, "An unexpected error occured", e);
  89. }
  90. try {
  91. if (response.hasFailed()) {
  92. this.callbackContext.error(response.toJSON());
  93. } else {
  94. this.callbackContext.success(response.toJSON());
  95. }
  96. } catch (JSONException e) {
  97. Log.e(TAG, "An unexpected error occured while creating HTTP response object", e);
  98. }
  99. }
  100. protected HttpRequest createRequest() throws JSONException {
  101. return new HttpRequest(this.url, this.method);
  102. }
  103. protected void prepareRequest(HttpRequest request) throws JSONException, IOException {
  104. request.followRedirects(this.followRedirects);
  105. request.readTimeout(this.timeout);
  106. request.acceptCharset("UTF-8");
  107. request.uncompress(true);
  108. if (this.tlsConfiguration.getHostnameVerifier() != null) {
  109. request.setHostnameVerifier(this.tlsConfiguration.getHostnameVerifier());
  110. }
  111. request.setSSLSocketFactory(this.tlsConfiguration.getTLSSocketFactory());
  112. // setup content type before applying headers, so user can override it
  113. this.setContentType(request);
  114. request.headers(JsonUtils.getStringMap(this.headers));
  115. }
  116. protected void setContentType(HttpRequest request) {
  117. if ("json".equals(this.serializer)) {
  118. request.contentType("application/json", "UTF-8");
  119. } else if ("utf8".equals(this.serializer)) {
  120. request.contentType("text/plain", "UTF-8");
  121. } else if ("raw".equals(this.serializer)) {
  122. request.contentType("application/octet-stream");
  123. } else if ("urlencoded".equals(this.serializer)) {
  124. // intentionally left blank, because content type is set in HttpRequest.form()
  125. } else if ("multipart".equals(this.serializer)) {
  126. request.contentType("multipart/form-data");
  127. }
  128. }
  129. protected void sendBody(HttpRequest request) throws Exception {
  130. if (this.data == null) {
  131. return;
  132. }
  133. if ("json".equals(this.serializer)) {
  134. request.send(this.data.toString());
  135. } else if ("utf8".equals(this.serializer)) {
  136. request.send(((JSONObject) this.data).getString("text"));
  137. } else if ("raw".equals(this.serializer)) {
  138. request.send(Base64.decode((String)this.data, Base64.DEFAULT));
  139. } else if ("urlencoded".equals(this.serializer)) {
  140. request.form(JsonUtils.getObjectMap((JSONObject) this.data));
  141. } else if ("multipart".equals(this.serializer)) {
  142. JSONArray buffers = ((JSONObject) this.data).getJSONArray("buffers");
  143. JSONArray names = ((JSONObject) this.data).getJSONArray("names");
  144. JSONArray fileNames = ((JSONObject) this.data).getJSONArray("fileNames");
  145. JSONArray types = ((JSONObject) this.data).getJSONArray("types");
  146. for (int i = 0; i < buffers.length(); ++i) {
  147. byte[] bytes = Base64.decode(buffers.getString(i), Base64.DEFAULT);
  148. String name = names.getString(i);
  149. if (fileNames.isNull(i)) {
  150. request.part(name, new String(bytes, "UTF-8"));
  151. } else {
  152. request.part(name, fileNames.getString(i), types.getString(i), new ByteArrayInputStream(bytes));
  153. }
  154. }
  155. }
  156. }
  157. protected void processResponse(HttpRequest request, CordovaHttpResponse response) throws Exception {
  158. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  159. request.receive(outputStream);
  160. response.setStatus(request.code());
  161. response.setUrl(request.url().toString());
  162. response.setHeaders(request.headers());
  163. if (request.code() >= 200 && request.code() < 300) {
  164. if ("text".equals(this.responseType) || "json".equals(this.responseType)) {
  165. String decoded = HttpBodyDecoder.decodeBody(outputStream.toByteArray(), request.charset());
  166. response.setBody(decoded);
  167. } else {
  168. response.setData(outputStream.toByteArray());
  169. }
  170. } else {
  171. response.setErrorMessage(HttpBodyDecoder.decodeBody(outputStream.toByteArray(), request.charset()));
  172. }
  173. }
  174. }