`
阿_剛
  • 浏览: 9199 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

JAVA 访问URL WEB页面读入

 
阅读更多
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;

import javax.swing.JTextArea;

public class Html_getter {

    public static void main(String[] args){
    Object o1 = null;
try {
o1 = new Getter5(new URL("http://www.yahoo.co.jp/"));
} catch (MalformedURLException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
((Getter5)o1).Show();
    }
}
class Getter5{
private String charset = "Shift_JIS";
private JTextArea htmlArea;

public Getter5(URL url){
htmlArea = new JTextArea();
        // Webページを読み込む
        try {
            // 接続
            URLConnection uc = url.openConnection();
            // HTMLを読み込む
            BufferedInputStream bis = new BufferedInputStream(uc.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(bis, charset));
            htmlArea.setText("");//初期化
            String line;
            while ((line = br.readLine()) != null) {
                htmlArea.append(line + "\n");
            }
        } catch (MalformedURLException ex) {
            htmlArea.setText("URLが不正です。");
            ex.printStackTrace();
        } catch (UnknownHostException ex) {
            htmlArea.setText("サイトが見つかりません。");
        } catch (IOException ex) {
            ex.printStackTrace();
        }   
    }
public void Show(){
System.out.println(htmlArea.getText());
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics