Ben Hsieh 8 лет назад
Родитель
Сommit
b0306cc30b

+ 4
- 173
src/android/src/main/java/com/RNFetchBlob/RNFetchBlob.java Просмотреть файл

@@ -19,10 +19,12 @@ import com.facebook.react.modules.core.DeviceEventManagerModule;
19 19
 import com.loopj.android.http.AsyncHttpClient;
20 20
 import com.loopj.android.http.AsyncHttpResponseHandler;
21 21
 import com.loopj.android.http.Base64;
22
+import com.loopj.android.http.MySSLSocketFactory;
22 23
 import com.loopj.android.http.RequestParams;
23 24
 
24 25
 import java.io.ByteArrayOutputStream;
25 26
 import java.io.File;
27
+import java.security.KeyStore;
26 28
 import java.util.HashMap;
27 29
 import java.util.Map;
28 30
 
@@ -158,183 +160,12 @@ public class RNFetchBlob extends ReactContextBaseJavaModule {
158 160
 
159 161
     @ReactMethod
160 162
     public void fetchBlob(ReadableMap options, String taskId, String method, String url, ReadableMap headers, String body, final Callback callback) {
161
-
162
-        RNFetchBlobConfig config = new RNFetchBlobConfig(options);
163
-
164
-        // use download manager instead of default HTTP implementation
165
-        if(config.addAndroidDownloads != null && config.addAndroidDownloads.hasKey("useDownloadManager")) {
166
-
167
-            if(config.addAndroidDownloads.getBoolean("useDownloadManager")) {
168
-                Uri uri = Uri.parse(url);
169
-                DownloadManager.Request req = new DownloadManager.Request(uri);
170
-                if(config.path != null) {
171
-                    Uri dest = null;
172
-                    dest = Uri.parse(config.path);
173
-                    req.setDestinationUri(dest);
174
-                }
175
-                // set headers
176
-                ReadableMapKeySetIterator it = headers.keySetIterator();
177
-                while (it.hasNextKey()) {
178
-                    String key = it.nextKey();
179
-                    req.addRequestHeader(key, headers.getString(key));
180
-                }
181
-                DownloadManager dm = (DownloadManager) this.getReactApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE);
182
-                dm.enqueue(req);
183
-                return;
184
-            }
185
-
186
-        }
187
-
188
-        try {
189
-            AsyncHttpClient req = new AsyncHttpClient();
190
-
191
-            AbstractHttpEntity entity = null;
192
-
193
-            // set headers
194
-            ReadableMapKeySetIterator it = headers.keySetIterator();
195
-            while (it.hasNextKey()) {
196
-                String key = it.nextKey();
197
-                req.addHeader(key, headers.getString(key));
198
-            }
199
-
200
-            // set body for POST and PUT
201
-            if(body != null && method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put")) {
202
-
203
-                byte [] blob;
204
-                // upload from storage
205
-                if(body.startsWith(filePathPrefix)) {
206
-                    String filePath = body.substring(filePathPrefix.length());
207
-                    entity = new FileEntity(new File(filePath));
208
-                }
209
-                else {
210
-                    blob = Base64.decode(body, 0);
211
-                    entity = new ByteArrayEntity(blob);
212
-                }
213
-                entity.setContentType(headers.getString("Content-Type"));
214
-            }
215
-
216
-            AsyncHttpResponseHandler handler;
217
-
218
-            // create handler
219
-            if(config.fileCache || config.path != null) {
220
-                handler = new RNFetchBlobFileHandler(this.getReactApplicationContext(), taskId, config, callback);
221
-                // if path format invalid, throw error
222
-                if (!((RNFetchBlobFileHandler)handler).isValid) {
223
-                    callback.invoke("RNFetchBlob fetch error, configuration path `"+ config.path  +"` is not a valid path.");
224
-                    return;
225
-                }
226
-            }
227
-            else
228
-                handler = new RNFetchBlobBinaryHandler(this.getReactApplicationContext(), taskId, callback);
229
-
230
-            // send request
231
-            switch(method.toLowerCase()) {
232
-                case "get" :
233
-                    req.get(url, handler);
234
-                    break;
235
-                case "post" :
236
-                    req.post(this.getReactApplicationContext(), url, entity, "octet-stream", handler);
237
-                    break;
238
-                case "put" :
239
-                    req.put(this.getReactApplicationContext(), url, entity, "octet-stream",handler);
240
-                    break;
241
-                case "delete" :
242
-                    req.delete(url, handler);
243
-                    break;
244
-            }
245
-        } catch(Exception error) {
246
-            callback.invoke( "RNFetchBlob serialize request data failed: " + error.getMessage() + error.getCause());
247
-        }
248
-
163
+        new RNFetchBlobReq(this.getReactApplicationContext(), options, taskId, method, url, headers, body, callback).run();
249 164
     }
250 165
 
251 166
     @ReactMethod
252 167
     public void fetchBlobForm(ReadableMap options, String taskId, String method, String url, ReadableMap headers, ReadableArray body, final Callback callback) {
253
-
254
-        RNFetchBlobConfig config = new RNFetchBlobConfig(options);
255
-        try {
256
-
257
-            AsyncHttpClient req = new AsyncHttpClient();
258
-
259
-            HttpEntity entity = null;
260
-
261
-            // set headers
262
-            if(headers != null) {
263
-                ReadableMapKeySetIterator it = headers.keySetIterator();
264
-                while (it.hasNextKey()) {
265
-                    String key = it.nextKey();
266
-                    req.addHeader(key, headers.getString(key));
267
-                }
268
-            }
269
-
270
-            // set body for POST and PUT
271
-            if(body != null && method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put")) {
272
-                Long tsLong = System.currentTimeMillis()/1000;
273
-                String ts = tsLong.toString();
274
-                String boundary = "RNFetchBlob".concat(ts);
275
-                MultipartEntityBuilder form = MultipartEntityBuilder.create();
276
-                form.setBoundary(boundary);
277
-                for( int i = 0; i< body.size(); i++) {
278
-                    ReadableMap map = body.getMap(i);
279
-                    String name = map.getString("name");
280
-                    if(!map.hasKey("data"))
281
-                        continue;
282
-                    String data = map.getString("data");
283
-                    // file field
284
-                    if(map.hasKey("filename")) {
285
-                        String filename = map.getString("filename");
286
-                        // upload from storage
287
-                        if(data.startsWith(filePathPrefix)) {
288
-                            File file = new File(data.substring(filePathPrefix.length()));
289
-                            form.addBinaryBody(name, file, ContentType.APPLICATION_OCTET_STREAM, filename);
290
-                        }
291
-                        // base64 embedded file content
292
-                        else {
293
-                            form.addBinaryBody(name, Base64.decode(data, 0), ContentType.APPLICATION_OCTET_STREAM, filename);
294
-                        }
295
-                    }
296
-                    // data field
297
-                    else {
298
-                        form.addTextBody(name, map.getString("data"));
299
-                    }
300
-                }
301
-                entity = form.build();
302
-                req.addHeader("Content-Type", headers.getString("Content-Type") + "; charset=utf8; boundary=" + boundary);
303
-            }
304
-
305
-            AsyncHttpResponseHandler handler;
306
-
307
-            // create handler
308
-            if(config.fileCache || config.path != null) {
309
-                handler = new RNFetchBlobFileHandler(this.getReactApplicationContext(), taskId, config, callback);
310
-                // if path format invalid, throw error
311
-                if (!((RNFetchBlobFileHandler)handler).isValid) {
312
-                    callback.invoke("RNFetchBlob fetch error, configuration path `"+ config.path  +"` is not a valid path.");
313
-                    return;
314
-                }
315
-            }
316
-            else
317
-                handler = new RNFetchBlobBinaryHandler(this.getReactApplicationContext(), taskId, callback);
318
-
319
-            // send request
320
-            switch(method.toLowerCase()) {
321
-                case "get" :
322
-                    req.get(url, handler);
323
-                    break;
324
-                case "post" :
325
-                    req.post(this.getReactApplicationContext(), url, entity, "multipart/form-data; charset=utf8", handler);
326
-                    break;
327
-                case "put" :
328
-                    req.put(this.getReactApplicationContext(), url, entity, "multipart/form-data",handler);
329
-                    break;
330
-                case "delete" :
331
-                    req.delete(url, handler);
332
-                    break;
333
-            }
334
-        } catch(Exception error) {
335
-            callback.invoke( "RNFetchBlob serialize request data failed: " + error.getMessage() + error.getCause());
336
-        }
337
-
168
+        new RNFetchBlobReq(this.getReactApplicationContext(), options, taskId, method, url, headers, body, callback).run();
338 169
     }
339 170
 
340 171
 }

+ 2
- 0
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobConfig.java Просмотреть файл

@@ -13,6 +13,7 @@ public class RNFetchBlobConfig {
13 13
     public String path;
14 14
     public String appendExt;
15 15
     public ReadableMap addAndroidDownloads;
16
+    public Boolean trusty;
16 17
 
17 18
     RNFetchBlobConfig(ReadableMap options) {
18 19
         if(options == null)
@@ -20,6 +21,7 @@ public class RNFetchBlobConfig {
20 21
         this.fileCache = options.hasKey("fileCache") ? options.getBoolean("fileCache") : false;
21 22
         this.path = options.hasKey("path") ? options.getString("path") : null;
22 23
         this.appendExt = options.hasKey("appendExt") ? options.getString("appendExt") : "";
24
+        this.trusty = options.hasKey("trusty") ? options.getBoolean("trusty") : false;
23 25
         if(options.hasKey("addAndroidDownloads")) {
24 26
             this.addAndroidDownloads = options.getMap("addAndroidDownloads");
25 27
         }

+ 1
- 1
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobPackage.java Просмотреть файл

@@ -19,7 +19,7 @@ import java.util.Collections;
19 19
 import java.util.List;
20 20
 
21 21
 /**
22
- * Created by xeiyan on 2016/4/29.
22
+ * Created by wkh237 on 2016/4/29.
23 23
  */
24 24
 public class RNFetchBlobPackage implements ReactPackage {
25 25
 

+ 231
- 0
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobReq.java Просмотреть файл

@@ -0,0 +1,231 @@
1
+package com.RNFetchBlob;
2
+
3
+import android.app.DownloadManager;
4
+import android.content.Context;
5
+import android.net.Uri;
6
+
7
+import com.facebook.react.bridge.Callback;
8
+import com.facebook.react.bridge.ReactApplicationContext;
9
+import com.facebook.react.bridge.ReadableArray;
10
+import com.facebook.react.bridge.ReadableMap;
11
+import com.facebook.react.bridge.ReadableMapKeySetIterator;
12
+import com.loopj.android.http.AsyncHttpClient;
13
+import com.loopj.android.http.AsyncHttpResponseHandler;
14
+import com.loopj.android.http.Base64;
15
+import com.loopj.android.http.MySSLSocketFactory;
16
+
17
+import java.io.File;
18
+import java.nio.charset.Charset;
19
+import java.security.KeyStore;
20
+
21
+import cz.msebera.android.httpclient.HttpEntity;
22
+import cz.msebera.android.httpclient.entity.AbstractHttpEntity;
23
+import cz.msebera.android.httpclient.entity.ByteArrayEntity;
24
+import cz.msebera.android.httpclient.entity.ContentType;
25
+import cz.msebera.android.httpclient.entity.FileEntity;
26
+import cz.msebera.android.httpclient.entity.mime.MultipartEntityBuilder;
27
+
28
+/**
29
+ * Created by wkh237 on 2016/6/21.
30
+ */
31
+public class RNFetchBlobReq implements Runnable{
32
+
33
+    final String filePathPrefix = "RNFetchBlob-file://";
34
+    ReactApplicationContext ctx;
35
+    RNFetchBlobConfig options;
36
+    String taskId;
37
+    String method;
38
+    String url;
39
+    String boundary;
40
+    ReadableMap headers;
41
+    Callback callback;
42
+    HttpEntity entity;
43
+    AsyncHttpClient req;
44
+    String type;
45
+
46
+    public RNFetchBlobReq(ReactApplicationContext ctx, ReadableMap options, String taskId, String method, String url, ReadableMap headers, String body, final Callback callback) {
47
+        this.ctx = ctx;
48
+        this.method = method;
49
+        this.options= new RNFetchBlobConfig(options);
50
+        this.taskId = taskId;
51
+        this.url = url;
52
+        this.headers = headers;
53
+        this.callback = callback;
54
+        this.req = new AsyncHttpClient();
55
+        if(body != null) {
56
+            type = "octet";
57
+            buildEntity(body);
58
+        }
59
+    }
60
+
61
+    public RNFetchBlobReq(ReactApplicationContext ctx, ReadableMap options, String taskId, String method, String url, ReadableMap headers, ReadableArray body, final Callback callback) {
62
+        this.ctx = ctx;
63
+        this.method = method;
64
+        this.options= new RNFetchBlobConfig(options);
65
+        this.taskId = taskId;
66
+        this.url = url;
67
+        this.headers = headers;
68
+        this.callback = callback;
69
+        this.req = new AsyncHttpClient();
70
+        if(body != null) {
71
+            type = "form";
72
+            buildFormEntity(body);
73
+        }
74
+    }
75
+
76
+    @Override
77
+    public void run() {
78
+
79
+        // use download manager instead of default HTTP implementation
80
+        if(options.addAndroidDownloads != null && options.addAndroidDownloads.hasKey("useDownloadManager")) {
81
+
82
+            if(options.addAndroidDownloads.getBoolean("useDownloadManager")) {
83
+                Uri uri = Uri.parse(url);
84
+                DownloadManager.Request req = new DownloadManager.Request(uri);
85
+                if(options.path != null) {
86
+                    Uri dest = null;
87
+                    dest = Uri.parse(options.path);
88
+                    req.setDestinationUri(dest);
89
+                }
90
+                // set headers
91
+                ReadableMapKeySetIterator it = headers.keySetIterator();
92
+                while (it.hasNextKey()) {
93
+                    String key = it.nextKey();
94
+                    req.addRequestHeader(key, headers.getString(key));
95
+                }
96
+                DownloadManager dm = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE);
97
+                dm.enqueue(req);
98
+                return;
99
+            }
100
+
101
+        }
102
+
103
+        try {
104
+
105
+            // use trusty SSL socket
106
+            if(this.options.trusty) {
107
+                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
108
+                trustStore.load(null, null);
109
+                MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
110
+                sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
111
+                req.setSSLSocketFactory(sf);
112
+            }
113
+
114
+            // set headers
115
+            if(headers != null) {
116
+                ReadableMapKeySetIterator it = headers.keySetIterator();
117
+                while (it.hasNextKey()) {
118
+                    String key = it.nextKey();
119
+                    req.addHeader(key, headers.getString(key));
120
+                }
121
+            }
122
+
123
+            if(type != null)
124
+            {
125
+                if(type == "octet")
126
+                    req.addHeader("Content-Type", "application/octet-stream");
127
+                else if(type == "form")
128
+                    req.addHeader("Content-Type", "multipart/form-data; charset=utf8; boundary="+boundary);
129
+            }
130
+
131
+            AsyncHttpResponseHandler handler;
132
+
133
+            // create handler
134
+            if(options.fileCache || options.path != null) {
135
+                handler = new RNFetchBlobFileHandler(ctx, taskId, options, callback);
136
+                // if path format invalid, throw error
137
+                if (!((RNFetchBlobFileHandler)handler).isValid) {
138
+                    callback.invoke("RNFetchBlob fetch error, configuration path `"+ options.path  +"` is not a valid path.");
139
+                    return;
140
+                }
141
+            }
142
+            else
143
+                handler = new RNFetchBlobBinaryHandler(this.ctx, taskId, callback);
144
+
145
+            // send request
146
+            switch(method.toLowerCase()) {
147
+                case "get" :
148
+                    req.get(url, handler);
149
+                    break;
150
+                case "post" :
151
+                    if(this.type == null || this.type.equalsIgnoreCase("octet"))
152
+                        req.post(ctx, url, entity, "application/octet-stream", handler);
153
+                    else
154
+                        req.post(ctx, url, entity, "multipart/form-data", handler);
155
+                    break;
156
+                case "put" :
157
+                    if(this.type == null || this.type.equalsIgnoreCase("octet"))
158
+                        req.post(ctx, url, entity, "application/octet-stream", handler);
159
+                    else
160
+                        req.post(ctx, url, entity, "multipart/form-data", handler);
161
+                    break;
162
+                case "delete" :
163
+                    req.delete(url, handler);
164
+                    break;
165
+            }
166
+        } catch(Exception error) {
167
+            callback.invoke( "RNFetchBlob serialize request data failed: " + error.getMessage() + error.getCause());
168
+        }
169
+    }
170
+
171
+    /**
172
+     * Build Mutipart body
173
+     * @param body  Body in array format
174
+     */
175
+    void buildFormEntity(ReadableArray body) {
176
+        if(body != null && (method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put"))) {
177
+            Long tsLong = System.currentTimeMillis()/1000;
178
+            String ts = tsLong.toString();
179
+            boundary = "RNFetchBlob".concat(ts);
180
+            MultipartEntityBuilder form = MultipartEntityBuilder.create();
181
+            form.setBoundary(boundary);
182
+            for( int i = 0; i< body.size(); i++) {
183
+                ReadableMap map = body.getMap(i);
184
+                String name = map.getString("name");
185
+                if(!map.hasKey("data"))
186
+                    continue;
187
+                String data = map.getString("data");
188
+                // file field
189
+                if(map.hasKey("filename")) {
190
+                    String filename = map.getString("filename");
191
+                    // upload from storage
192
+                    if(data.startsWith(filePathPrefix)) {
193
+                        File file = new File(data.substring(filePathPrefix.length()));
194
+                        form.addBinaryBody(name, file, ContentType.APPLICATION_OCTET_STREAM, filename);
195
+                    }
196
+                    // base64 embedded file content
197
+                    else {
198
+                        form.addBinaryBody(name, Base64.decode(data, 0), ContentType.APPLICATION_OCTET_STREAM, filename);
199
+                    }
200
+                }
201
+                // data field
202
+                else {
203
+                    form.addTextBody(name, map.getString("data"));
204
+                }
205
+            }
206
+            entity = form.build();
207
+        }
208
+    }
209
+
210
+    /**
211
+     * Build Octet-Stream body
212
+     * @param body  Body in string format
213
+     */
214
+    void buildEntity(String body) {
215
+        // set body for POST and PUT
216
+        if(body != null && (method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put"))) {
217
+
218
+            byte [] blob;
219
+            // upload from storage
220
+            if(body.startsWith(filePathPrefix)) {
221
+                String filePath = body.substring(filePathPrefix.length());
222
+                entity = new FileEntity(new File(filePath));
223
+            }
224
+            else {
225
+                blob = Base64.decode(body, 0);
226
+                entity = new ByteArrayEntity(blob);
227
+            }
228
+        }
229
+
230
+    }
231
+}