Bladeren bron

Fix Android content type and content length issue #94

Ben Hsieh 8 jaren geleden
bovenliggende
commit
c7fc337401

+ 29
- 10
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobBody.java Bestand weergeven

@@ -65,6 +65,12 @@ public class RNFetchBlobBody extends RequestBody{
65 65
         requestType = type;
66 66
         this.rawBody = rawBody;
67 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 76
     @Override
@@ -96,7 +102,19 @@ public class RNFetchBlobBody extends RequestBody{
96 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 118
         long total = 0;
101 119
         // upload from storage
102 120
         if (rawBody.startsWith(RNFetchBlobConst.FILE_PREFIX)) {
@@ -106,31 +124,32 @@ public class RNFetchBlobBody extends RequestBody{
106 124
             if (RNFetchBlobFS.isAsset(orgPath)) {
107 125
                 try {
108 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 128
                     requestStream = RNFetchBlob.RCTContext.getAssets().open(assetName);
111 129
                 } catch (IOException e) {
112
-//                        e.printStackTrace();
130
+                    RNFetchBlobUtils.emitWarningEvent(e.getLocalizedMessage());
113 131
                 }
114 132
             } else {
115 133
                 File f = new File(RNFetchBlobFS.normalizePath(orgPath));
116 134
                 try {
117 135
                     if(!f.exists())
118 136
                         f.createNewFile();
119
-                    contentLength = f.length();
137
+                    total += f.length();
120 138
                     requestStream = new FileInputStream(f);
121 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 143
         } else {
126 144
             try {
127 145
                 byte[] bytes = Base64.decode(rawBody, 0);
128
-                contentLength = bytes.length;
129 146
                 requestStream = new ByteArrayInputStream(bytes);
147
+                total += requestStream.available();
130 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,7 +192,7 @@ public class RNFetchBlobBody extends RequestBody{
173 192
                             InputStream in = ctx.getAssets().open(assetName);
174 193
                             pipeStreamToFileStream(in, os);
175 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 198
                     // data from normal files
@@ -184,7 +203,7 @@ public class RNFetchBlobBody extends RequestBody{
184 203
                             pipeStreamToFileStream(fs, os);
185 204
                         }
186 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,7 +303,7 @@ public class RNFetchBlobBody extends RequestBody{
284 303
                             long length = ctx.getAssets().open(assetName).available();
285 304
                             total += length;
286 305
                         } catch (IOException e) {
287
-
306
+                            RNFetchBlobUtils.emitWarningEvent(e.getLocalizedMessage());
288 307
                         }
289 308
                     }
290 309
                     // general files

+ 28
- 13
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobReq.java Bestand weergeven

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