Skip to content

Commit 20f4a7f

Browse files
authored
Merge pull request RonRadtke#45 from pcardon/android/decode
Android response encode/decode issue
2 parents 404d40b + c8e9507 commit 20f4a7f

File tree

1 file changed

+8
-11
lines changed

1 file changed

+8
-11
lines changed

android/src/main/java/com/ReactNativeBlobUtil/ReactNativeBlobUtilReq.java

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
import java.nio.ByteBuffer;
4747
import java.nio.charset.CharacterCodingException;
4848
import java.nio.charset.Charset;
49-
import java.nio.charset.CharsetEncoder;
49+
import java.nio.charset.CharsetDecoder;
5050
import java.security.KeyStore;
5151
import java.util.ArrayList;
5252
import java.util.Arrays;
@@ -558,26 +558,23 @@ private void done(Response resp) {
558558
}
559559
// response data directly pass to JS context as string.
560560
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.
564561
byte[] b = resp.body().bytes();
565-
CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
566562
if(responseFormat == ResponseFormat.BASE64) {
567563
callback.invoke(null, ReactNativeBlobUtilConst.RNFB_RESPONSE_BASE64, android.util.Base64.encodeToString(b, Base64.NO_WRAP));
568564
return;
569565
}
570566
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);
575573
callback.invoke(null, ReactNativeBlobUtilConst.RNFB_RESPONSE_UTF8, utf8);
576574
}
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,
578576
// it's binary data, so send it as a normal string
579577
catch(CharacterCodingException ignored) {
580-
581578
if(responseFormat == ResponseFormat.UTF8) {
582579
String utf8 = new String(b);
583580
callback.invoke(null, ReactNativeBlobUtilConst.RNFB_RESPONSE_UTF8, utf8);

0 commit comments

Comments
 (0)