练习URLConnection网络访问方法

仿照IE浏览器,设计一简单的网站访问程序

主窗口

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import java.awt.event.ActionListener;
import java.io.IOException;

public class frame {

	private JFrame frame;
	private JTextField textField;
	private final JButton button_1 = new JButton("保存代码");

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					frame window = new frame();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public frame() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setResizable(false);
		frame.setTitle("测试");
		frame.setBounds(200, 300, 600, 500);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		JLabel lblUrl = new JLabel("URL:");
		lblUrl.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
		lblUrl.setBounds(6, 6, 37, 16);
		frame.getContentPane().add(lblUrl);
		
		textField = new JTextField();
		textField.setBounds(45, 2, 342, 26);
		frame.getContentPane().add(textField);
		textField.setColumns(10);
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(6, 34, 588, 438);
		frame.getContentPane().add(scrollPane);
		
		JTextArea textArea = new JTextArea();
		scrollPane.setViewportView(textArea);
		
		JButton btnNewButton = new JButton("获取代码");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new getSource(textField.getText(),textArea);
			}
		});
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					new Save(textArea);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		button_1.setBounds(450, 3, 78, 26);
		frame.getContentPane().add(button_1);
		btnNewButton.setBounds(381, 2, 78, 29);
		frame.getContentPane().add(btnNewButton);
		
		JButton btnNewButton_1 = new JButton("保存图片");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new SavePicture(textField);
			}
		});
		btnNewButton_1.setBounds(522, 2, 78, 29);
		frame.getContentPane().add(btnNewButton_1);
	}
}

获取源代码

import java.net.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;

import java.io.*;

public class getSource {
	private String url;
	private JTextArea area;
	public getSource(String url,JTextArea area) {
		this.url = url;
		this.area = area;
		URL();
	}
	public void URL()
	{
		try {
			//打开HttpURLConnection进行读取
			URL u = new URL(url);
			HttpURLConnection con = (HttpURLConnection)u.openConnection();
			InputStream raw = con.getInputStream();
			InputStream buffer = new BufferedInputStream(raw);//添加数据缓冲流
			Reader reader = new InputStreamReader(buffer);//读取缓冲流中的数据
			int c;
			String source ="";
			while((c=reader.read())!=-1)
			{
				source+=(char)c;
			}
			reader.close();//关闭流
			area.setText(source);
			JOptionPane.showMessageDialog(null,"获取源代码成功!");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

保存代码

import javax.swing.JOptionPane;
import javax.swing.JTextArea;

import java.io.*;

public class Save {
	private JTextArea area;
	public Save(JTextArea area) throws IOException
	{
		this.area = area;
		String source = area.getText();
		File file =  new File("D:\\index.html");//创建文件
		if(!file.exists())//文件不存在
		{
			file.createNewFile();
		}
		FileWriter writer = new FileWriter(file);
		BufferedWriter bufw = new BufferedWriter(writer);
		bufw.write(source);
		bufw.close();
		writer.close();
		JOptionPane.showMessageDialog(null, "保存代码成功");
	}
}
保存图片
import java.io.*;
import java.net.URL;

import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class SavePicture {
	public SavePicture(JTextField field)
	{
		String source = field.getText();
		 try {
	            URL url=new URL(source);//图片地址
	            InputStream is=url.openStream();//打开网址
	            File image=new File("D:\\pic8.jpg");//创建文件
	            if(!image.exists())
	            {
	            	image.createNewFile();
	            }
	            FileOutputStream fos=new FileOutputStream(image);//输出流
	            byte[] b=new byte[2048];//需为2的倍数
	            int n=is.read(b);//读取字节的个数,每次读2048个字节
	            while(n!=-1){//-1表示读完
//	              fos.write(b1);//写入所有字节流
	                fos.write(b,0,n);//第0个字节开始,写入n个字节
	                n=is.read(b);
	            }
	            //弹出提示框
	           JOptionPane.showMessageDialog(null, "图片保存成功");
	            //关闭流
	            is.close();
	            fos.close();
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42103959/article/details/80633075