简体   繁体   中英

Which String could give an UnsupportedEncodingException when using Base64 encoding

Looking for a test case in which either the Base64 encode decode may break with an UnsupportedEncodingException or the decoded String will not be same as original. Intention is to create a set of test cases.

import java.io.UnsupportedEncodingException;
import java.util.Base64;

public class Encode {

    public static void main(String[] args)  {
        System.out.println(" Hellow Encode" );
        String[] test = {"+","+1"," !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"
                ,"+name `~ name =="};
        try {
            for(String mes : test) {
                System.out.print(mes);
                String s=Base64.getEncoder().encodeToString(mes.getBytes("utf-8"));
                System.out.print("\t"+s);
                byte[] decoButes=Base64.getDecoder().decode(s);
                String decoStr =  new String(decoButes, "utf-8");
                System.out.println(decoStr.equals(mes)); // If Falls Sucess
            }
        }catch(UnsupportedEncodingException e){
            System.out.println("SUCESS"); // Wish if this is executed
        }
    }
}

No Base 64 encoded string can cause an UnsupportedEncodingException in your program. The exception is raised if the charsetName parameter of String.getBytes(String) or String(byte[], String) is invalid. Since it is a constant in your program and the constant is a valid charset name, it will never be raised.

You can simplify your program by using other String methods:

Instead of:

mes.getBytes("utf-8")

Use:

mes.getBytes(StandardCharsets.UTF_8)

And instead of:

new String(decoButes, "utf-8")

Use:

new String(decoButes, StandardCharsets.UTF_8)

That way, the charset/encoding is checked at compile-time and the related exception handling code can and must be removed. Furthermore, there is no need to create a test case for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM