java入门教程:网络通信例子(一)

java网络通信例基础入门教程一

 

文件ExtendString.java

 

package chapter09.sample9_1;

public class ExtendString {
	  public ExtendString() {
	  }
	  /**
	   去掉字符串两端的空白字符,并将字符串转化为中国的标准字符gb2312的字符串.
	   */
	  public String CS(String str) { //去掉字符串2端的空白字符
	      try {
	          if (str == null)
	              return "";
	          str = str.trim();
	          if (str == null)
	              return "";
	          str = new String(str.getBytes("8859_1"), "GBK");
	      }
	      catch (Exception e) {
	          System.out.println(e);
	      }
	      return str;
	  }


}

 

文件MailSender.java

 

package chapter09.sample9_1;
import java.io.*;
import java.util.*;
import java.io.File; 
import java.io.UnsupportedEncodingException; 
import java.util.ArrayList; 
import java.util.Date; 
import java.util.Properties; 

import javax.activation.DataHandler; 
import javax.activation.DataSource; 
import javax.activation.FileDataSource; 
import javax.mail.Authenticator; 
import javax.mail.BodyPart; 
import javax.mail.Message; 
import javax.mail.MessagingException; 
import javax.mail.Multipart; 
import javax.mail.PasswordAuthentication; 
import javax.mail.SendFailedException; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeBodyPart; 
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimeMultipart; 

import org.htmlparser.Node; 
import org.htmlparser.Parser; 
import org.htmlparser.tags.ImageTag; 
import org.htmlparser.util.ParserException; 



public class MailSender {
	private String username = null;  //邮件发送帐号用户名 
    private String userpasswd = null; //邮件发送帐号用户口令 
    protected BodyPart messageBodyPart = null; 
    protected Multipart multipart = new MimeMultipart("related"); 
    protected MimeMessage mailMessage = null; 
    protected Session mailSession = null; 
    protected Properties mailProperties = System.getProperties(); 
    protected InternetAddress mailFromAddress = null; 
    protected InternetAddress mailToAddress = null; 
    protected Authenticator authenticator = null; 
    protected String mailSubject = ""; 
    protected Date mailSendDate = null; 

    /** 
     * 构造函数 
     * @param smtpHost 
     * @param username 
     * @param password 
     */ 
    protected MailSender(String smtpHost, String username, String password) { 
        this.username = username; 
        this.userpasswd = password; 
        mailProperties.put("mail.smtp.host", smtpHost); 
        mailProperties.put("mail.smtp.auth", "true"); //设置smtp认证,很关键的一句 
        mailSession = Session.getDefaultInstance(mailProperties); 
        mailMessage = new MimeMessage(mailSession); 
        messageBodyPart = new MimeBodyPart(); 
    } 
    /** 
     * 构造一个纯文本邮件发送实例 
     * @param smtpHost 
     * @param username 
     * @param password 
     * @return 
     */ 
    public static MailSender getTextMailSender(String smtpHost, String username, String password) { 
        return new MailSender(smtpHost,username,password) { 
            public void setMailContent(String mailContent) throws MessagingException { 
                messageBodyPart.setText(mailContent); 
                multipart.addBodyPart(messageBodyPart); 
            } 
        }; 
    } 
    /** 
     * 构造一个超文本邮件发送实例 
     * @param smtpHost 
     * @param username 
     * @param password 
     * @return 
     */ 
    public static MailSender getHtmlMailSender(String smtpHost, String username, String password) { 
        return new MailSender(smtpHost,username,password) { 
            private ArrayList arrayList1 = new ArrayList(); 
            private ArrayList arrayList2 = new ArrayList(); 

            public void setMailContent(String mailContent) throws MessagingException { 
                String htmlContent = getContent(""; 
                    messageBodyPart.setHeader("Content-ID", contentId); 
                    messageBodyPart.setFileName((String) arrayList1.get(i)); 
                    multipart.addBodyPart(messageBodyPart); 
                } 
            } 

            //处理要发送的html文件,主要是针对html文件中的图片 
            private String getContent(String searchString, String mailContent) { 
                try { 
                    Parser parser = Parser.createParser(new String(mailContent.getBytes(), ISO8859_1)); 
                    Node[] images = parser.extractAllNodesThatAre(ImageTag.class); 
                    for(int i=0;i"; 
            //sendmail.setMailContent(content); // 
            //sendmail.setAttachments("E:\\ConList.exe");//文章附件 
            sendmail.setMailFrom("[email protected]");//显示谁发送的 
            sendmail.setMailTo(toAddress, "to");//cc抄送,bcc 暗送 
            //sendmail.setMailTo(toAddress, "cc");//设置抄送给... 
            //开始发送邮件 
            System.out.println("正在发送邮件,请稍候......."); 
            sendmail.sendMail(); 
            System.out.println("恭喜你,邮件已经成功发送!"); 
        } catch (Exception ex) { 
            ex.printStackTrace(); 
        } 
    } 
}

 

文件Sample9_1.java

 

package chapter09.sample9_1;

import java.io.*;
import java.net.*;

public class Sample9_1 {
	public static void main(String[] args)
			{
				try
				{
					//创建URL对象
					URL url=new URL("http://www.sina.com");
					//打开指向资源的输入流
					InputStream in=url.openStream();
					//将输入流由字节流转换为字符流
					InputStreamReader isr=new InputStreamReader(in);
					//将输入流封装为缓冲输入处理流
					BufferedReader br=new BufferedReader(isr);
					//创建输出流,并指定目标文件
					BufferedWriter bw=new BufferedWriter(new FileWriter("c:/URL.html"));
					//对输出流进一步进行封装
					PrintWriter pw=new PrintWriter(bw);
					//声明临时字符串引用
					String temps=null;
					//从输入流中获取资源并测试是否读取完毕
					while((temps=br.readLine())!=null)
					{

						//将获取的数据写如目标文件
						pw.println(temps);
					}
					//打印提示信息
					System.out.println("恭喜您,资源已经获取完毕,并将其写入了URL.html文件中!!!");
					//关闭输入流与输出流
					pw.close();
					br.close();
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}
}

海口

你可能感兴趣的:(Java,java网络通信)