|
46 | 46 | import java.nio.ByteBuffer;
|
47 | 47 | import java.nio.charset.CharacterCodingException;
|
48 | 48 | import java.nio.charset.Charset;
|
49 |
| -import java.nio.charset.CharsetEncoder; |
| 49 | +import java.nio.charset.CharsetDecoder; |
50 | 50 | import java.security.KeyStore;
|
51 | 51 | import java.util.ArrayList;
|
52 | 52 | import java.util.Arrays;
|
@@ -558,26 +558,23 @@ private void done(Response resp) {
|
558 | 558 | }
|
559 | 559 | // response data directly pass to JS context as string.
|
560 | 560 | else {
|
561 |
| - // #73 Check if the response data contains valid UTF8 string, since BASE64 |
562 |
| - // encoding will somehow break the UTF8 string format, to encode UTF8 |
563 |
| - // string correctly, we should do URL encoding before BASE64. |
564 | 561 | byte[] b = resp.body().bytes();
|
565 |
| - CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder(); |
566 | 562 | if(responseFormat == ResponseFormat.BASE64) {
|
567 | 563 | callback.invoke(null, ReactNativeBlobUtilConst.RNFB_RESPONSE_BASE64, android.util.Base64.encodeToString(b, Base64.NO_WRAP));
|
568 | 564 | return;
|
569 | 565 | }
|
570 | 566 | try {
|
571 |
| - encoder.encode(ByteBuffer.wrap(b).asCharBuffer()); |
572 |
| - // if the data contains invalid characters the following lines will be |
573 |
| - // skipped. |
574 |
| - String utf8 = new String(b); |
| 567 | + // Attempt to decode the incoming response data to determine whether it contains a valid UTF8 string |
| 568 | + Charset charSet = Charset.forName("UTF-8"); |
| 569 | + CharsetDecoder decoder = charSet.newDecoder(); |
| 570 | + decoder.decode(ByteBuffer.wrap(b)); |
| 571 | + // If the data contains invalid characters the following lines will be skipped. |
| 572 | + String utf8 = new String(b, charSet); |
575 | 573 | callback.invoke(null, ReactNativeBlobUtilConst.RNFB_RESPONSE_UTF8, utf8);
|
576 | 574 | }
|
577 |
| - // This usually mean the data is contains invalid unicode characters but still valid data, |
| 575 | + // This usually means the data contains invalid unicode characters but still valid data, |
578 | 576 | // it's binary data, so send it as a normal string
|
579 | 577 | catch(CharacterCodingException ignored) {
|
580 |
| - |
581 | 578 | if(responseFormat == ResponseFormat.UTF8) {
|
582 | 579 | String utf8 = new String(b);
|
583 | 580 | callback.invoke(null, ReactNativeBlobUtilConst.RNFB_RESPONSE_UTF8, utf8);
|
|
0 commit comments