开发者

UTF-8 encoding vs Base-64 Encoding

I want to encode a file it may be image or any pdf and send it to server. Which type of Encoding and decoding I have to follow. (Both server and client is in our company. we can write logic in both place). UTF-8 Encoding is by default supported in java. and to use Base-64 encoding I have to import external jar. for simple texts both the ways are working fine. I am using tcp socket programming.

Using UTF-8 Encoding

String str = "This is my Sample application";
        String urlEncodedData = URLEncoder.encode(str, "UTF-8"); // Encoding with UTF-8
        System.out.println("..after URL Encodingencoding..."+urlEncodedData );
        String retrievedData = URLDecoder.decode(urlEncodedData , "UTF-8");// Dec开发者_如何学编程oding with UTF-8
        System.out.println("..after decoding..."+retrievedData ); 

Using Base-64 (Using commons.codec jar of apache

byte[] b =Base64.encodeBase64(str.getBytes()); //Encoding  base 64
        Base64.decodeBase64(b); // Decoding with Base 64


UTF-8 is a text encoding - a way of encoding text as binary data.

Base64 is in some ways the opposite - it's a way of encoding arbitrary binary data as ASCII text.

If you need to encode arbitrary binary data as text, Base64 is the way to go - you mustn't try to treat arbitrary binary data as if it's UTF-8 encoded text data.

However, you may well be able to transfer the file to the server just as binary data in the first place - it depends on what transport you're using.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜