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方法實現郵件發送
下一篇mac php編輯器