Java之------socket查看指定URL的Web页编辑器及HTML文档

本例只能用于查看比较简单的网页,像是现在jsp开发的网页有很多地方时无法显示的,但这种程序还是值得学习一下的

package cn.hncu.url;

import java.util.Date;
import java.text.SimpleDateFormat;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.net.*;

public class HtmlJFrame extends JFrame implements ActionListener, ChangeListener
{
    private URL urls[];                                    //URL对象数组
    private JComboBox combox;                      //组合框,输入或选择URL地址
    private JTextField text;                               //文本行,显示文件属性
    private JTabbedPane tab;                               //选项卡窗格,每页显示一个文件
    private String charset="GBK";                          //字符集名称

    public HtmlJFrame()
    {
        super("查看指定URL的Web页编辑器及HTML文档");
        this.setBounds(150,100,1024,600);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        String urls[]={"http://www.phei.com.cn",
                       "http://www.baidu.com",
                       "http://www.google.com",
                       "http://www.sina.com",
                       "file://localhost/D:/Program Files/Java/docs/api/index.html"};
        this.combox = new JComboBox(urls);         //组合框,显示URL地址
        this.combox.setEditable(true);                     //组合框可编辑
        this.getContentPane().add(this.combox,"North");
        this.combox.addActionListener(this);               //组合框注册单击事件监听器
        
        this.getContentPane().add(this.tab=new JTabbedPane());//选项卡窗格
        this.tab.addChangeListener(this);                  //注册选择事件监听器
        
        this.getContentPane().add(this.text=new JTextField(),"South");//文件属性文本行
        this.setVisible(true);
        this.urls = new URL[20];                           //创建URL对象数组
        this.combox.setSelectedIndex(0);                   //选中组合框第1项,触发单击事件,执行actionPerformed()方法
    }
    
    public void actionPerformed(ActionEvent ev)             //组合框选择或单击回车键时触发执行
    {
        String urlname=(String)combox.getSelectedItem();   //获得组合框选中项字符串
        int i=tab.getTabCount();                           //tab当前页数,即下一页序号
        try
        {
            this.urls[i] = new URL(urlname);               //创建一个URL对象,若文件不存在,抛出异常,则不添加tab页
            String filename = this.urls[i].toString();     //URL路径名
            for (int j=i-1; j>=0; j--)                     //在已有页面中查找,不重复打开文件
                if(this.tab.getTitleAt(j).equals(filename))//getTitleAt(j)返回tab第j页标题
                {
                    this.tab.setSelectedIndex(j);          //选中指定tab页,触发ChangeEvent事件
                    return;
                }

            JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT); //创建垂直分割窗格
            split.setOneTouchExpandable(true);             //提供一键展开按钮,快速展开/折叠分隔条
            split.setDividerLocation(200);                 //设置水平分隔条位置
            split.add(new JScrollPane(new JEditorPane(this.urls[i])));//创建指定URL的编辑器窗格
            JTextArea text_content = new JTextArea();      //文本区,显示源文档
            split.add(new JScrollPane(text_content));
            this.tab.addTab(filename, split);              //tab添加新页,页中添加分割窗格
            this.tab.setSelectedIndex(this.tab.getTabCount()-1); //选中tab指定新页,触发ChangeEvent事件
            this.readFrom(this.urls[i], this.charset, text_content);//读取url指定文本中的字符串
        }
        catch(MalformedURLException ex)
        {   JOptionPane.showMessageDialog(this, "字符串指定未知协议错误");
        }
        catch (FileNotFoundException ex)
        {   JOptionPane.showMessageDialog(this, "\""+urls[i].getFile()+"\"文件不存在");
        }
        catch (IOException ex)
        {   JOptionPane.showMessageDialog(this, "IO错,读取"+urls[i].getFile()+"文件不成功");
        }
    }

    public void stateChanged(ChangeEvent ev)                //当单击选项卡窗格的页标题时触发执行
    {                                                      //通过文件对象获得文件属性
        this.charset="GBK";                                //字符集名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        int i=tab.getSelectedIndex();
        String protocol = urls[i].getProtocol();
        String str="协议:"+protocol+",";
        try
        {
            if (protocol.equalsIgnoreCase("file"))         //FILE协议,比较相等忽略字母大小写
            {
                File file = new File(urls[i].getFile());   //获得文件对象
                text.setText(str+"本机:"+InetAddress.getLocalHost().toString()+
                    ",文件:"+file.getAbsolutePath()+",字符集:"+this.charset+",长度:"+
                    file.length()+"B,修改日期:"+sdf.format(new Date(file.lastModified())));
            }
            if (protocol.equalsIgnoreCase("http"))         //HTTP协议
            {
                URLConnection urlconn = urls[i].openConnection();
                String content=urlconn.getContentType();   //获得文件类型,可能包含字符集
                int j=content.indexOf("charset=");
                if (j!=-1)
                    charset=content.substring(j+8);        //获得字符集
                text.setText(str+"主机:"+urls[i].getHost()+",端口:"+urls[i].getDefaultPort()+
                    ",IP地址:"+InetAddress.getByName(urls[i].getHost()).getHostAddress()+
                    ",文件:"+urls[i].getFile()+",长度:"+urlconn.getContentLength()+
                    "B,类型:"+urlconn.getContentType()+",字符集:"+charset+
                    ",修改日期:"+sdf.format(new Date(urlconn.getLastModified())));
            }
        }
        catch(UnknownHostException ex)
        {
            JOptionPane.showMessageDialog(this, "找不到指定主机的IP地址");
        }
        catch(IOException ex)
        {
            JOptionPane.showMessageDialog(this, "IO错,读取"+this.urls[i].getFile()+"文件不成功");
        }
    }
    
    //读取url指定文本中的字符串,添加到text文本区中,charset指定字符集
    public void readFrom(URL url, String charset, JTextArea text) throws IOException
    {
        InputStreamReader ir = new InputStreamReader(url.openStream(), charset);
        BufferedReader br = new BufferedReader(ir);    //将字节输入流转换成字符输入流,创建字符缓冲输入流
        String line = null;
        while ((line=br.readLine())!=null)             //从字符缓冲输入流中读取一行字符串
            text.append(line+"\r\n");
        br.close();
        ir.close();
    }
    
    public static void main(String args[])
    {
        new HtmlJFrame();
    }
}

在界面的最上侧输入需要查询的网址即可,如下:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值