Browse Source

Fix Android content type and content length issue #94

Ben Hsieh 8 years ago
parent
commit
c7fc337401

+ 29
- 10
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobBody.java View File

65
         requestType = type;
65
         requestType = type;
66
         this.rawBody = rawBody;
66
         this.rawBody = rawBody;
67
         mime = contentType;
67
         mime = contentType;
68
+        if(rawBody != null) {
69
+            if(requestType == RNFetchBlobReq.RequestType.AsIs)
70
+                contentLength = rawBody.length();
71
+            else
72
+                contentLength = caculateOctetContentLength();
73
+        }
68
     }
74
     }
69
 
75
 
70
     @Override
76
     @Override
96
         buffer.flush();
102
         buffer.flush();
97
     }
103
     }
98
 
104
 
99
-    private void caculateOctetContentLength() {
105
+    boolean clearRequestBody() {
106
+        try {
107
+            if (bodyCache != null && bodyCache.exists()) {
108
+                bodyCache.delete();
109
+            }
110
+        } catch(Exception e) {
111
+            RNFetchBlobUtils.emitWarningEvent(e.getLocalizedMessage());
112
+            return false;
113
+        }
114
+        return true;
115
+    }
116
+
117
+    private long caculateOctetContentLength() {
100
         long total = 0;
118
         long total = 0;
101
         // upload from storage
119
         // upload from storage
102
         if (rawBody.startsWith(RNFetchBlobConst.FILE_PREFIX)) {
120
         if (rawBody.startsWith(RNFetchBlobConst.FILE_PREFIX)) {
106
             if (RNFetchBlobFS.isAsset(orgPath)) {
124
             if (RNFetchBlobFS.isAsset(orgPath)) {
107
                 try {
125
                 try {
108
                     String assetName = orgPath.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
126
                     String assetName = orgPath.replace(RNFetchBlobConst.FILE_PREFIX_BUNDLE_ASSET, "");
109
-                    contentLength = RNFetchBlob.RCTContext.getAssets().openFd(assetName).getLength();
127
+                    total += RNFetchBlob.RCTContext.getAssets().openFd(assetName).getLength();
110
                     requestStream = RNFetchBlob.RCTContext.getAssets().open(assetName);
128
                     requestStream = RNFetchBlob.RCTContext.getAssets().open(assetName);
111
                 } catch (IOException e) {
129
                 } catch (IOException e) {
112
-//                        e.printStackTrace();
130
+                    RNFetchBlobUtils.emitWarningEvent(e.getLocalizedMessage());
113
                 }
131
                 }
114
             } else {
132
             } else {
115
                 File f = new File(RNFetchBlobFS.normalizePath(orgPath));
133
                 File f = new File(RNFetchBlobFS.normalizePath(orgPath));
116
                 try {
134
                 try {
117
                     if(!f.exists())
135
                     if(!f.exists())
118
                         f.createNewFile();
136
                         f.createNewFile();
119
-                    contentLength = f.length();
137
+                    total += f.length();
120
                     requestStream = new FileInputStream(f);
138
                     requestStream = new FileInputStream(f);
121
                 } catch (Exception e) {
139
                 } catch (Exception e) {
122
-//                        callback.invoke(e.getLocalizedMessage(), null);
140
+                    RNFetchBlobUtils.emitWarningEvent("RNetchBlob error when counting content length: " +e.getLocalizedMessage());
123
                 }
141
                 }
124
             }
142
             }
125
         } else {
143
         } else {
126
             try {
144
             try {
127
                 byte[] bytes = Base64.decode(rawBody, 0);
145
                 byte[] bytes = Base64.decode(rawBody, 0);
128
-                contentLength = bytes.length;
129
                 requestStream = new ByteArrayInputStream(bytes);
146
                 requestStream = new ByteArrayInputStream(bytes);
147
+                total += requestStream.available();
130
             } catch(Exception ex) {
148
             } catch(Exception ex) {
131
-                Log.e("error", ex.getLocalizedMessage());
149
+                RNFetchBlobUtils.emitWarningEvent("RNetchBlob error when counting content length: " +ex.getLocalizedMessage());
132
             }
150
             }
133
         }
151
         }
152
+        return total;
134
     }
153
     }
135
 
154
 
136
     /**
155
     /**
173
                             InputStream in = ctx.getAssets().open(assetName);
192
                             InputStream in = ctx.getAssets().open(assetName);
174
                             pipeStreamToFileStream(in, os);
193
                             pipeStreamToFileStream(in, os);
175
                         } catch (IOException e) {
194
                         } catch (IOException e) {
176
-                            Log.e("RNFetchBlob", "Failed to create form data asset :" + orgPath + ", " + e.getLocalizedMessage() );
195
+                            RNFetchBlobUtils.emitWarningEvent("RNFetchBlob Failed to create form data asset :" + orgPath + ", " + e.getLocalizedMessage() );
177
                         }
196
                         }
178
                     }
197
                     }
179
                     // data from normal files
198
                     // data from normal files
184
                             pipeStreamToFileStream(fs, os);
203
                             pipeStreamToFileStream(fs, os);
185
                         }
204
                         }
186
                         else {
205
                         else {
187
-                            Log.e("RNFetchBlob", "Failed to create form data from path :" + orgPath + "file not exists.");
206
+                            RNFetchBlobUtils.emitWarningEvent("RNFetchBlob Failed to create form data from path :" + orgPath + ", file not exists.");
188
                         }
207
                         }
189
                     }
208
                     }
190
                 }
209
                 }
284
                             long length = ctx.getAssets().open(assetName).available();
303
                             long length = ctx.getAssets().open(assetName).available();
285
                             total += length;
304
                             total += length;
286
                         } catch (IOException e) {
305
                         } catch (IOException e) {
287
-
306
+                            RNFetchBlobUtils.emitWarningEvent(e.getLocalizedMessage());
288
                         }
307
                         }
289
                     }
308
                     }
290
                     // general files
309
                     // general files

+ 28
- 13
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobReq.java View File

25
 import java.io.IOException;
25
 import java.io.IOException;
26
 import java.io.InputStream;
26
 import java.io.InputStream;
27
 import java.net.MalformedURLException;
27
 import java.net.MalformedURLException;
28
+import java.net.SocketException;
28
 import java.net.SocketTimeoutException;
29
 import java.net.SocketTimeoutException;
29
 import java.net.URL;
30
 import java.net.URL;
30
 import java.nio.ByteBuffer;
31
 import java.nio.ByteBuffer;
81
     Callback callback;
82
     Callback callback;
82
     long contentLength;
83
     long contentLength;
83
     long downloadManagerId;
84
     long downloadManagerId;
85
+    RNFetchBlobBody requestBody;
84
     RequestType requestType;
86
     RequestType requestType;
85
     ResponseType responseType;
87
     ResponseType responseType;
86
     WritableMap respInfo;
88
     WritableMap respInfo;
207
             if(method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put")) {
209
             if(method.equalsIgnoreCase("post") || method.equalsIgnoreCase("put")) {
208
                 String cType = getHeaderIgnoreCases(mheaders, "Content-Type").toLowerCase();
210
                 String cType = getHeaderIgnoreCases(mheaders, "Content-Type").toLowerCase();
209
 
211
 
210
-                if(cType == null) {
212
+                if(rawRequestBodyArray != null) {
213
+                    requestType = RequestType.Form;
214
+                }
215
+                else if(cType == null || cType.isEmpty()) {
211
                     builder.header("Content-Type", "application/octet-stream");
216
                     builder.header("Content-Type", "application/octet-stream");
212
                     requestType = RequestType.SingleFile;
217
                     requestType = RequestType.SingleFile;
213
                 }
218
                 }
235
             // set request body
240
             // set request body
236
             switch (requestType) {
241
             switch (requestType) {
237
                 case SingleFile:
242
                 case SingleFile:
238
-                    builder.method(method, new RNFetchBlobBody(
243
+                    requestBody = new RNFetchBlobBody(
239
                             taskId,
244
                             taskId,
240
                             requestType,
245
                             requestType,
241
                             rawRequestBody,
246
                             rawRequestBody,
242
                             MediaType.parse(getHeaderIgnoreCases(mheaders, "content-type"))
247
                             MediaType.parse(getHeaderIgnoreCases(mheaders, "content-type"))
243
-                    ));
248
+                    );
249
+                    builder.method(method, requestBody);
244
                     break;
250
                     break;
245
                 case AsIs:
251
                 case AsIs:
246
-                    builder.method(method, new RNFetchBlobBody(
252
+                    requestBody = new RNFetchBlobBody(
247
                             taskId,
253
                             taskId,
248
                             requestType,
254
                             requestType,
249
                             rawRequestBody,
255
                             rawRequestBody,
250
                             MediaType.parse(getHeaderIgnoreCases(mheaders, "content-type"))
256
                             MediaType.parse(getHeaderIgnoreCases(mheaders, "content-type"))
251
-                    ));
257
+                    );
258
+                    builder.method(method, requestBody);
252
                     break;
259
                     break;
253
                 case Form:
260
                 case Form:
254
                     String boundary = "RNFetchBlob-" + taskId;
261
                     String boundary = "RNFetchBlob-" + taskId;
255
-                    builder.method(method, new RNFetchBlobBody(
262
+                    requestBody = new RNFetchBlobBody(
256
                             taskId,
263
                             taskId,
257
                             requestType,
264
                             requestType,
258
                             rawRequestBodyArray,
265
                             rawRequestBodyArray,
259
                             MediaType.parse("multipart/form-data; boundary="+ boundary)
266
                             MediaType.parse("multipart/form-data; boundary="+ boundary)
260
-                    ));
267
+                    );
268
+                    builder.method(method, requestBody);
261
                     break;
269
                     break;
262
 
270
 
263
                 case WithoutBody:
271
                 case WithoutBody:
301
                                 break;
309
                                 break;
302
                         }
310
                         }
303
                         return originalResponse.newBuilder().body(extended).build();
311
                         return originalResponse.newBuilder().body(extended).build();
304
-                    } catch(Exception ex) {
305
-                        RNFetchBlobUtils.emitWarningEvent(ex.getLocalizedMessage());
312
+                    }
313
+                    catch (SocketException ex) {
314
+                        timeout = true;
315
+                    }
316
+                    catch(Exception ex) {
317
+                        RNFetchBlobUtils.emitWarningEvent("RNFetchBlob error when sending request : " + ex.getLocalizedMessage());
318
+
306
                     }
319
                     }
307
                     return chain.proceed(chain.request());
320
                     return chain.proceed(chain.request());
308
                 }
321
                 }
337
                     }
350
                     }
338
                     else
351
                     else
339
                         callback.invoke(e.getLocalizedMessage(), null, null);
352
                         callback.invoke(e.getLocalizedMessage(), null, null);
340
-                    removeTaskInfo();
353
+                    releaseTaskResource();
341
                 }
354
                 }
342
 
355
 
343
                 @Override
356
                 @Override
367
 
380
 
368
         } catch (Exception error) {
381
         } catch (Exception error) {
369
             error.printStackTrace();
382
             error.printStackTrace();
370
-            taskTable.remove(taskId);
383
+            releaseTaskResource();
371
             callback.invoke("RNFetchBlob request error: " + error.getMessage() + error.getCause());
384
             callback.invoke("RNFetchBlob request error: " + error.getMessage() + error.getCause());
372
         }
385
         }
373
     }
386
     }
375
     /**
388
     /**
376
      * Remove cached information of the HTTP task
389
      * Remove cached information of the HTTP task
377
      */
390
      */
378
-    private void removeTaskInfo() {
391
+    private void releaseTaskResource() {
379
         if(taskTable.containsKey(taskId))
392
         if(taskTable.containsKey(taskId))
380
             taskTable.remove(taskId);
393
             taskTable.remove(taskId);
381
         if(uploadProgressReport.containsKey(taskId))
394
         if(uploadProgressReport.containsKey(taskId))
382
             uploadProgressReport.remove(taskId);
395
             uploadProgressReport.remove(taskId);
383
         if(progressReport.containsKey(taskId))
396
         if(progressReport.containsKey(taskId))
384
             progressReport.remove(taskId);
397
             progressReport.remove(taskId);
398
+        if(requestBody != null)
399
+            requestBody.clearRequestBody();
385
     }
400
     }
386
 
401
 
387
     /**
402
     /**
455
         }
470
         }
456
         if(!resp.isSuccessful())
471
         if(!resp.isSuccessful())
457
             resp.body().close();
472
             resp.body().close();
458
-        removeTaskInfo();
473
+        releaseTaskResource();
459
     }
474
     }
460
 
475
 
461
     /**
476
     /**