본문 바로가기

프로그램/java

url, urlconnection 을 이용하여 웹페이지 읽어오기

반응형
자바캔 사이트 참조하였음, http://javacan.tistory.com/entry/35

URL 클래스를 이용하여 특정 web page에 접근할 수 있음
URLConnection 을 통해서 stream 을 얻고 이를 통해 내용을 가져오고 parameter를 넘기고 할 수 있음

            // contents 가져오기
            URL url = new URL("http", "127.0.0.1", 8000, "/TestWeb/index2.jsp");
            // openConnection 말고 connect() 라는 것도 있음.
            URLConnection conn = url.openConnection();
           
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
           
            char[] buff = new char[512];
           
            int len = -1;
           
            while((len = br.read(buff)) != -1) {
                System.out.println(new String(buff, 0, len));
            }
           
            br.close();
            is.close();


            // 파라메터를 처리해보자.
            Properties prop = new Properties();
            prop.setProperty("name", "Lee");
            prop.setProperty("age", "31");
           
            String encodeStr = encodeString(prop);
           
            System.out.println("===== encodeStr : " + encodeStr);
           
            URL url2 = new URL("http://127.0.0.1:8000/TestWeb/index2.jsp?" + encodeStr);
            URLConnection conn2 = url2.openConnection();
           
            conn2.setUseCaches(false);
           
            InputStream is2 = conn2.getInputStream();
            BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));
           
            char[] buff2 = new char[512];
            int len2 = -1;
           
            while((len2 = br2.read(buff2)) != -1) {
                System.out.println(new String(buff2, 0, len2));
            }
           
            br2.close();
            is2.close();


            // post 로 넘겨보자.
            URL url3 = new URL("http://127.0.0.1:8000/TestWeb/index2.jsp");
            URLConnection conn3 = url3.openConnection();
           
            conn3.setDoInput(true);
            conn3.setDoOutput(true);
           
            conn3.setUseCaches(false);
           
            conn3.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
           
            DataOutputStream out = null;
           
            try {
                out = new DataOutputStream(conn3.getOutputStream());
                out.writeBytes(encodeStr);
                out.flush();
            } catch (Exception e) {
            } finally {
                if(out != null) out.close();
            }
           
            InputStream is3 = conn3.getInputStream();
            BufferedReader br3 = new BufferedReader(new InputStreamReader(is3));
           
            char[] buff3 = new char[512];
            int len3 = -1;
           
            while((len3 = br3.read(buff3)) != -1) {
                System.out.println(new String(buff3, 0, len3));
            }
           
            br3.close();
            is3.close();