Java

Get title from remote web page (HttpURLConnection 사용)

빅토르최·2015년 12월 17일·조회 3,065
<%@ page import="java.io.BufferedReader" %>
<%@ page import="java.io.InputStreamReader" %>
<%@ page import="java.net.HttpURLConnection" %>
<%@ page import="java.net.MalformedURLException" %>
<%@ page import="java.net.NoRouteToHostException" %>
<%@ page import="java.net.UnknownHostException" %>
<%@ page import="java.net.URL" %>
<%
        String inputUrl = request.getParameter("url");
        out.println("** URL = "+inputUrl);

        URL url = null;
        BufferedReader br = null;
        HttpURLConnection uc = null;
        String urlLine;

        long startTime = System.currentTimeMillis();

        try {
                url = new URL("http://"+inputUrl);
                uc = (HttpURLConnection)url.openConnection();
                uc.setConnectTimeout(10000);
                uc.setReadTimeout(10000);
                br = new BufferedReader(new InputStreamReader(uc.getInputStream()));

                while ((urlLine = br.readLine()) != null) {
                        if ( urlLine.indexOf("<title>") >= 0 ) {
                                int indexStart = urlLine.indexOf("<title>")+"<title>".length();
                                int indexEnd = urlLine.indexOf("</title>");
                                out.println("<br>** Result = "+urlLine.substring(indexStart,indexEnd));
                                break;
                        }
                }
        } catch(MalformedURLException me) {
                out.println("<br>** Log = MalformedURL");
        } catch(UnknownHostException ue) {
                out.println("<br>** Log = UnknownHost");
        } catch(NoRouteToHostException ne) {
                out.println("<br>** Log = NoRouteToHost");
        } catch(Exception e) {
                out.println("<br>** Log = Exception");
                //e.printStackTrace();
        } finally {
                if ( uc != null ) uc.disconnect();
                if ( br != null ) br.close();
        }

        out.println("<br>** Elapsed = "+(System.currentTimeMillis()-startTime)+" ms");
%>

댓글 0

로그인 후 댓글을 남길 수 있습니다.

아직 댓글이 없습니다.