java UTF-8 编码与 Base-64 编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6792003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:17:04  来源:igfitidea点击:

UTF-8 encoding vs Base-64 Encoding

java

提问by Jon Skeet

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 Encodingis by default supported in java. and to use Base-64encoding I have to import external jar. for simple texts both the ways are working fine. I am using tcp socket programming.

我想编码一个文件,它可能是图像或任何 pdf 并将其发送到服务器。我必须遵循哪种类型的编码和解码。(服务器和客户端都在我们公司。我们可以在两个地方编写逻辑)。Java 中默认支持UTF-8 编码。要使用Base-64编码,我必须导入外部 jar。对于简单的文本,两种方式都可以正常工作。我正在使用 tcp 套接字编程。

Using UTF-8 Encoding

使用 UTF-8 编码

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");// Decoding with UTF-8
        System.out.println("..after decoding..."+retrievedData ); 

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

使用 Base-64(使用 apache 的 commons.codec jar

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

回答by Jon Skeet

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

UTF-8 是一种文本编码——一种将文本编码为二进制数据的方法。

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

Base64 在某些方面正好相反——它是一种将任意二进制数据编码为 ASCII 文本的方法。

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

如果您需要将任意二进制数据编码为文本,Base64 是可行的方法 - 您不能尝试将任意二进制数据视为 UTF-8 编码的文本数据。

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.

但是,您可能首先可以将文件作为二进制数据传输到服务器 - 这取决于您使用的传输方式。