본문 바로가기

Java SE/URLConnection 01

URLConnection 01

/* URL, URLConnection 을 이용한 웹상의 파일(HTML, Image, swf 등)복사해 오기.
* URL클래스를 이용하여 URLConnection객체를 얻고, URLConnection.getInputStream()을 호출하면,
* InputStream 을 얻을 수 있다. 이 스트림을 이용하여 Google.co.kr의 첫 페이지 html데이터를
* 복사해서 로컬 시스템에 google.html으로 저장해 보세요
*/

import java.io.*;
import java.net.*;

class  URLConnectionTest {
 public static void main(String[] args) throws IOException  {

  URL url = new URL("http://www.google.co.kr");
  URLConnection conn = url.openConnection();

  InputStream in = conn.getInputStream();

  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  PrintWriter pw = new PrintWriter("google.html");
  String line = "";

  while((line=br.readLine())!=null) {
   pw.println(line); // 파일에 저장
   System.out.println(line); // 화면 출력
  }
  br.close();
  pw.close();
 }
}