当先锋百科网

首页 1 2 3 4 5 6 7

Java是一种跨平台性的编程语言,拥有着广泛的应用。它的运用范围涉及到网络编程,以及和各种应用层协议的对接。下面将重点介绍如何让Java和应用层协议相结合。

应用层协议:HTTP
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) 
System.out.println(inputLine);
in.close();
}
}

在上述代码中,用到了Java内置的URLConnection类和BufferedReader类,通过这两个类可以构建一个与指定URL进行通信的URLConnection对象。然后,使用BufferedReader逐行读取返回页面的每一行内容,打印出来进行展示。

应用层协议:SMTP
public class SendEmail {
public static void main(String[] args) {
final String username = "myusername@gmail.com";
final String password = "mypassword";
String fromEmail = "myusername@gmail.com";
String toEmail = "receiveremail@gmail.com";
String subject = "Test";
String body = "This is a test email";
String smtpHost = "smtp.gmail.com";
int smtpPort = 587;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", smtpPort);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromEmail));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toEmail));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
System.out.println("Email sent!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}

在上述代码中,用到了JavaMail API提供的类,通过该库可以实现发邮件功能。在这个例子里,需要设置以下内容:发送者的邮箱地址、密码、以及SMTP服务器的地址和端口号。然后构建Session对象, 邮件的消息体通过MimeMessage类实现,并通过Transport类中的send方法实现邮件发送