Java 實現窗口中點擊按鈕通過URL截取網頁內容

寫得很詳細了,註釋也詳細,就不解釋了

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class HTMLContent{

	public static void main(String[] args) {
		new URLContentDemo();
	}
}

class URLContentDemo extends JFrame{
	JFrame window;
	JTextField url;
	JTextArea html;
	JButton confirm;
	JPanel contentPanel;

	//初始化
	public URLContentDemo(){
		window=new JFrame("HTML Code Viewer");
		window.setLayout(null);
		window.setSize(800, 800);//設置大小
		window.setLocationRelativeTo(null);//設置居中
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//設置可關閉
		window.setLayout(null);//設置絕對佈局(窗口裏面的內容不會隨着窗口的改變而改變)
		window.setResizable(false);//設置窗口不可拉伸改變大小
		//設置URL標籤
		JLabel username_label =new JLabel("URL:");
		username_label.setFont(new Font("URL:", 1, 30));//設置字體大小
		username_label.setBounds(20,20,100,50);//設置位置和大小
		window.add(username_label);
		//設置URL文本框
		url=new JTextField();
		url.setFont(new Font("", 0, 20));
		url.setBounds(100, 20, 500, 50);
		window.add(url);
		//設置按鈕
		confirm=new JButton("Confirm");
		confirm.setBounds(650, 20, 100, 50);
		//按鈕點擊事件監聽
		confirm.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				html.setText(queryURLContent(url.getText()));
			}
		});
		window.add(confirm);

		//設置HTML文本框
		html=new JTextArea ();
		html.setLineWrap(true);//自動換行
		html.setWrapStyleWord(true);//自動適配每行字體
		html.setEditable(false);//不可編輯
		html.setFont(new Font("", 0, 20));//文本域內字體大小
		html.setBackground(new Color(244, 244, 244));//文本域背景
		//設置文本域滾動效果
		JScrollPane scrollpane=new JScrollPane(html);
		scrollpane.setBounds(20, 100, 750, 600);
		scrollpane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		window.add(scrollpane);

		window.setVisible(true);//設置面板可見
	}

	public String queryURLContent(String urlStr) {
		if(null == urlStr || "".equals(urlStr)) {
			JOptionPane.showMessageDialog(null, "請輸入URL地址", "URL輸入錯誤", JOptionPane.ERROR_MESSAGE);
			return "";
		}
		if(!verifyUrl(urlStr)) {
			JOptionPane.showMessageDialog(null, "請輸入正確的URL地址", "URL格式錯誤", JOptionPane.ERROR_MESSAGE);
			return "";
		}
		StringBuilder sb = null;
		boolean isConnection = false;
		try {
			//創建一個URL實例
			URL url = new URL(urlStr);
			sb = new StringBuilder();
			try {
				//檢測當前輸入URL是否是可用鏈接
				HttpURLConnection.setFollowRedirects(false);
				HttpURLConnection con = (HttpURLConnection) url.openConnection();
				con.setRequestMethod("HEAD");
				isConnection = con.getResponseCode() == HttpURLConnection.HTTP_OK;
			}catch (Exception e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(null, "該URL不存在:【UnknownHostException】", "URL異常提示", JOptionPane.ERROR_MESSAGE);
			}
			if (isConnection) {
				try {
					//通過URL的openStrean方法獲取URL對象所表示的自願字節輸入流
					InputStream is = url.openStream();
					InputStreamReader isr = new InputStreamReader(is,"utf-8");
					//爲字符輸入流添加緩衝
					BufferedReader br = new BufferedReader(isr);
					String data = br.readLine();//讀取數據
					while (data!=null){//循環讀取數據
						sb.append(data);//輸出數據
						data = br.readLine();
					}
					br.close();
					isr.close();
					is.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					JOptionPane.showMessageDialog(null, "URL內容獲取失敗:【IOException】", "URL異常提示", JOptionPane.ERROR_MESSAGE);
				}
			} 
		} catch (MalformedURLException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, "URL鏈接轉換失敗:【MalformedURLException】", "URL異常提示", JOptionPane.ERROR_MESSAGE);
		} 
		return sb.toString();
	}
	
	/**
	 * 驗證是否是URL
	 * @param url
	 * @return
	 */
	public static boolean verifyUrl(String url){
		String regEx ="[a-zA-z]+://[^\\s]*";
		//忽略大小寫
		Pattern pattern = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(url);
		boolean rs = matcher.matches();
		return rs;

	}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章