-2

I was trying to remove line breaks, but with this code below I can't proceed to remove it with replace() method.

private String encryptBase64(String data){
    byte[] values = null;

    try{
        values = data.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    String encrypted = Base64.encodeToString(values, Base64.DEFAULT);
        encrypted.replace("\r\n", "");
    Log.i("base64", encrypted);
    return encrypted;
}

As the code above, it's clear that I tried to remove line breaks but the code failed to do it. How to remove the line breaks?

Screenshot : base64 Log

Wiguna R
  • 157
  • 5
  • 19

3 Answers3

2

I have solution for your problem , You have to use URLEncoder to encode such string to pass in url. Example :

private String encryptBase64(String data){
byte[] values = null;
try{
    values = data.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}
String encrypted = Base64.encodeToString(values, Base64.DEFAULT);
// encrypted.replace("\r\n", "");
Log.i("base64", encrypted);
// =========== use this line of code ===============
    try {
            url_encode_val = URLEncoder.encode(encrypted, "utf-8");
            Log.e("encryptData_To url::", url_encode_val);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

return url_encode_val;
}
Amit Sharma
  • 645
  • 5
  • 13
0

Just replace encrypted = encrypted.replaceAll("(\\r|\\n|\\r\\n)+", ""); instead of encrypted.replace("\n", "");

Abhishek Patel
  • 4,280
  • 1
  • 24
  • 38
0

What you can do is:

String stringAsProfImg = android.util.Base64.encodeToString(byteArrayOfImg, android.util.Base64.DEFAULT);

Or what I am doing is converting a bitmap image to byte array and then converting byte array to BASE64 String.

Below is an example:

ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byteArrayOfImg = stream.toByteArray();
                bitmapImage.recycle();
                bitmapImage = null;
                stringAsProfImg =android.util.Base64.encodeToString(byteArrayOfImg, android.util.Base64.DEFAULT);
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
Anand Saggam
  • 57
  • 1
  • 8