|
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 @@ private void done(Response resp) {
|
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);
|
|
0 commit comments