【参加讨论】1 public class codecs {
2 private codecs() {} // do not instantiate this class
3 public final static string base64encode(string strinput) {
4 if (strinput == null) return null;
5 byte bytedata[] = new byte[strinput.length()];
6 strinput.getbytes(0, strinput.length(), bytedata, 0);
7 return new string(base64encode(bytedata), 0);
8 }
9 public final static byte[] base64encode(byte[] bytedata) {
10 if (bytedata == null) return null;
11 int isrcidx; // index into source (bytedata)
12 int idestidx; // index into destination (bytedest)
13 byte bytedest[] = new byte[((bytedata.length+2)/3)*4];
14 for (isrcidx=0, idestidx=0; isrcidx >> 2) & 077);
16 bytedest[idestidx++] = (byte) ((bytedata[isrcidx+1] >>> 4) & 017 |
(bytedata[isrcidx] << 4) & 077); 17 bytedest[idestidx++]="(byte)" ((bytedata[isrcidx+2]>>> 6) & 003 |
(bytedata[isrcidx+1] << 2) & 077); 18 bytedest[idestidx++]="(byte)" (bytedata[isrcidx+2] & 077); 19 } 20 if (isrcidx < bytedata.length) { 21 bytedest[idestidx++]="(byte)" ((bytedata[isrcidx]>>> 2) & 077);
22 if (isrcidx >> 4) & 017 |
(bytedata[isrcidx] << 4) & 077); 24 bytedest[idestidx++]="(byte)" ((bytedata[isrcidx+1] << 2) & 077); 25 } 26 else 27 bytedest[idestidx++]="(byte)" ((bytedata[isrcidx] << 4) & 077); 28 } 29 for (isrcidx="0;" isrcidx < idestidx; isrcidx++) { 30 if (bytedest[isrcidx] < 26) bytedest[isrcidx]="(byte)(bytedest[isrcidx]" + 'a'); 31 else if (bytedest[isrcidx] < 52) bytedest[isrcidx]="(byte)(bytedest[isrcidx]" + 'a'-26); 32 else if (bytedest[isrcidx] < 62) bytedest[isrcidx]="(byte)(bytedest[isrcidx]" + '0'-52); 33 else if (bytedest[isrcidx] < 63) bytedest[isrcidx]="+" ; 34 else bytedest[isrcidx]="/" ; 35 } 36 for ( ; isrcidx < bytedest.length; isrcidx++) 37 bytedest[isrcidx]="=" ; 38 return bytedest; 39 } 40 }
1-2定义public的codecs类和一个不能被用户调用的构造函数。通常,这个类不应被例示。
3-8定义一个encodebase64()方法函数。它的参数类型是string类型,返回base64编码的string。 它通过调用string。getbytes()并将结果数组传送至encodebase64(byte[])来完成函数的 功能。
9-39定义一个encodebase64()方法函数。参数为字符数组,返回base64编码的数组数组。
10如果参数值为null,退出方法函数。
11-13定义工作变量,其中字节dest数组包含了返回调用者的编码。注意,转换后的数组 比输入数组大约大三分之一。这是因为每个三字节s组被转换成四个字节。
14-19循环遍历整个输入数组,每次24比特,把这三个8比特组转换成四个两两之间相距二 比特的6比特组。这段代码比最初出现时简单。仔细学习,看看和前面的例子有什么不同。
20-28如果输入数组的字节s数目不是3的倍数,则转换余下的1或2个字节。
29-35把所得的编码数据作为base64码表的下标。(base64码表在rfc1521中说明)
36-37把目标串中的没有使用的字符置为'='。
38返回给调用者基于based64的编码。
我们已经取得了很重要的进展。到目前为止,我们已能序列化对象并将它放入内存,把它 转化为基于base64编码,目的是使用e-mail工具将它发给目标用户。作为我们目前进展的 总结,下面有一个代码片断,它生成一个bugreport对象实例,把它序列化并放入内存,然后 转化为base64编码。
1 import java.io.*;
2 import codecs.base64encode;
:
3 bugreport bug = new bugreport(1.0, "crashes when spell checker invoked", 2);
4 字 节arrayoutputstream os = new 字 节arrayoutputstream();
5 bug.save(os);
6 string strserializedbug = os.tostring();
7 strserializedbug = codecs.base64encode(strserializedbug);
和smtp服务器连接
如果你想发一封邮件,必须通过以下五个步骤:
1.为smtp服务器申请一个域名
2.建立一个tcp/ip的会话(session)
3.在服务器上登录
4.填写收信人的地址
5.撰写邮件的内容
下面分别就这些步骤进行讨论。
为smtp服务器申请一个域名
正如你发送普通信件一样,你首先得找一个邮局。对居民区和商业单位来说这是一件非 常简单的事,因为邮筒就在门口。internet上的电子邮件也同样简单。