一个基于SSL的简单浏览器(使用Swing)

xiaoxiao2021-02-27  473

//代码如下

import javax.swing.text.*; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.swing.*; import java.net.*; import java.io.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import javax.swing.text.html.*; import java.beans.*; public class SimpleWebBrowser extends JFrame implements HyperlinkListener,ActionListener{   private JTextField jtf=new JTextField(80);    private JEditorPane jep=new JEditorPane();   private String initialPage="";   private String host="localhost";   private int port=8888;   private SSLSocket socket;   public SimpleWebBrowser(String title) throws IOException{     super(title);          jtf.setText("");     jtf.addActionListener(this);     jep.setEditable(false);     jep.addHyperlinkListener(this);       //监听editorKit属性被重新设置的事件     jep.addPropertyChangeListener("editorKit", new PropertyChangeListener(){//注册一个PropertyChangeListener       public void propertyChange(PropertyChangeEvent evt){         EditorKit kit = jep.getEditorKit();           if(kit.getClass() == HTMLEditorKit.class) {             ((HTMLEditorKit)kit).setAutoFormSubmission(false);//按手工方式提交表单           }         }       });     JPanel northPanel = new JPanel();///     add(northPanel, BorderLayout.NORTH);     JButton solidButton = new JButton("网址:");//按钮     JButton searchButton = new JButton("浏览");     northPanel.add(solidButton);     northPanel.add(jtf);;     northPanel.add(searchButton);     add(new JScrollPane(jep));                    searchButton.addActionListener(new ActionListener() {点击按钮 @Override public void actionPerformed(ActionEvent e) { try { initialPage=jtf.getText();///将url中的网址放入 try { communicate();//握手 } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //String info="http://www.javathinker.org"; jep.setPage(initialPage);//?/发送请求,接受响应并·解析网页 } catch (IOException e1) { showError(initialPage); } } });//关闭按钮          pack();//自适应 setVisible(true);//可视化 setBounds(100,200,1100,700); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE);   }        public void showError(String url){      jep.setContentType("text/html");       jep.setText("<html>无法打开网页:"+url+"。输入的URL不合法,或者网页不存在。</html>");   }   public static void main(String[] args) throws IOException{     SimpleWebBrowser browser=new SimpleWebBrowser("浏览器");   }      public void actionPerformed(ActionEvent evt){     try{       jep.setPage(jtf.getText());       System.out.println("4");     }catch(Exception e){        showError(jtf.getText());     }   }   /** 处理用户选择超级链接或者提交表单事件 */   public void hyperlinkUpdate(HyperlinkEvent evt){     try{        if (evt.getClass() == FormSubmitEvent.class) {  //处理提交表单事件         FormSubmitEvent fevt = (FormSubmitEvent)evt;         URL url=fevt.getURL(); //获得URL         String method=fevt.getMethod().toString(); //获得请求方式         String data=fevt.getData(); //获得表单数据                 if(method.equals("GET")){  //如果为GET请求方式            jep.setPage(url.toString());            jtf.setText(url.toString()); //把文本框设为用户选择的超级链接         }else if(method.equals("POST")){  //如果为POST请求方式            URLConnection uc=url.openConnection();             //发送HTTP响应正文            System.out.println("1");            uc.setDoOutput(true);//设置是否可以获得输出流            OutputStreamWriter out=new OutputStreamWriter(uc.getOutputStream());             out.write(data);            //System.out.println(data);            out.close();                       //接收HTTP响应正文                InputStream in=uc.getInputStream();            ByteArrayOutputStream buffer=new ByteArrayOutputStream();            byte[] buff=new byte[1024];              int len=-1;            while((len=in.read(buff))!=-1){              buffer.write(buff,0,len);            }            in.close();           // System.out.println("2");            jep.setText(new String(buffer.toByteArray()));            jtf.setText(url.toString()); //把文本框设为用户选择的超级链接           }       }else if(evt.getEventType()==HyperlinkEvent.EventType.ACTIVATED){  //处理用户选择的超级链接               System.out.println("3");         jep.setPage(evt.getURL());         jtf.setText(evt.getURL().toString()); //把文本框设为用户选择的超级链接        }             }catch(Exception e){        showError(evt.getURL().toString());     }   }   //**************************  public void communicate()throws Exception{  System.setProperty("javax.net.ssl.trustStore", "D:\\myeclipse2016_workSpace\\SSLWeb\\test.keys");    SSLSocketFactory factory=(SSLSocketFactory)SSLSocketFactory.getDefault();    socket=(SSLSocket)factory.createSocket();    SocketAddress remoteAddr=new InetSocketAddress(host, port);    socket.connect(remoteAddr);        String[] supported=socket.getSupportedCipherSuites();    socket.setEnabledCipherSuites(supported);    System.out.println(socket.getUseClientMode()? "客户模式":"服务器模式");    StringBuffer sb=new StringBuffer("GET "+"/"+" HTTP/1.1\r\n");    sb.append("Host: localhost\r\n");    sb.append("Accept: */*\r\n");    sb.append("Accept-Language: zh-cn\r\n");    sb.append("Accept-Encoding: gzip, deflate\r\n");    sb.append("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)\r\n");    sb.append("Connection: Keep-Alive\r\n\r\n");    //发出HTTP请求    OutputStream socketOut=socket.getOutputStream();//SSL就在握手    socketOut.write(sb.toString().getBytes());//SSL就在握手           BufferedReader br=getReader(socket);    String data;    while((data=br.readLine())!=null){      System.out.println(data);          }           // socket.close();  }  private PrintWriter getWriter(SSLSocket socket)throws IOException{    OutputStream socketOut = socket.getOutputStream();    return new PrintWriter(socketOut,true);  }  private BufferedReader getReader(SSLSocket socket)throws IOException{    InputStream socketIn = socket.getInputStream();    return new BufferedReader(new InputStreamReader(socketIn));  } }   

//结果

转载请注明原文地址: https://www.6miu.com/read-431.html

最新回复(0)