Skip to content
This repository was archived by the owner on Mar 16, 2019. It is now read-only.

Commit f118228

Browse files
committed
Fix response unicode issue on Android #73
1 parent 3c9d0d9 commit f118228

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

src/android/src/main/java/com/RNFetchBlob/RNFetchBlobReq.java

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,13 @@
3030
import java.net.MalformedURLException;
3131
import java.net.SocketTimeoutException;
3232
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;
3340
import java.util.HashMap;
3441
import java.util.concurrent.TimeUnit;
3542

@@ -405,8 +412,24 @@ private void done(Response resp) {
405412
callback.invoke(null, info, dest);
406413
}
407414
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;
408419
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+
}
410433
}
411434
} catch (IOException e) {
412435
callback.invoke("RNFetchBlob failed to encode response data to BASE64 string.", null);

0 commit comments

Comments
 (0)