Browse Source

Fix response unicode issue on Android #73

Ben Hsieh 8 years ago
parent
commit
f118228c18
1 changed files with 24 additions and 1 deletions
  1. 24
    1
      src/android/src/main/java/com/RNFetchBlob/RNFetchBlobReq.java

+ 24
- 1
src/android/src/main/java/com/RNFetchBlob/RNFetchBlobReq.java View File

@@ -30,6 +30,13 @@ import java.io.InputStream;
30 30
 import java.net.MalformedURLException;
31 31
 import java.net.SocketTimeoutException;
32 32
 import java.net.URL;
33
+import java.net.URLEncoder;
34
+import java.nio.ByteBuffer;
35
+import java.nio.CharBuffer;
36
+import java.nio.charset.CharacterCodingException;
37
+import java.nio.charset.Charset;
38
+import java.nio.charset.CharsetDecoder;
39
+import java.nio.charset.CharsetEncoder;
33 40
 import java.util.HashMap;
34 41
 import java.util.concurrent.TimeUnit;
35 42
 
@@ -405,8 +412,24 @@ public class RNFetchBlobReq extends BroadcastReceiver implements Runnable {
405 412
                         callback.invoke(null, info, dest);
406 413
                     }
407 414
                     else {
415
+                        // we should check if the response data is a UTF8 string, because BASE64
416
+                        // encoding will somehow break the UTF8 string format. In order to encode
417
+                        // UTF8 string correctly, we should do URL encoding before BASE64.
418
+                        String utf8Str;
408 419
                         byte[] b = resp.body().bytes();
409
-                        callback.invoke(null, getResponseInfo(resp), android.util.Base64.encodeToString(b, Base64.NO_WRAP));
420
+                        CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
421
+                        try {
422
+                            encoder.encode(ByteBuffer.wrap(b).asCharBuffer());
423
+                            // if the data can be encoded to UTF8 append URL encode
424
+                            b = URLEncoder.encode(new String(b), "UTF-8").getBytes();
425
+                        }
426
+                        // This usually mean the data is binary data
427
+                        catch(CharacterCodingException e) {
428
+
429
+                        }
430
+                        finally {
431
+                            callback.invoke(null, getResponseInfo(resp), android.util.Base64.encodeToString(b, Base64.NO_WRAP));
432
+                        }
410 433
                     }
411 434
                 } catch (IOException e) {
412 435
                     callback.invoke("RNFetchBlob failed to encode response data to BASE64 string.", null);