Java
소스에서 네트워크(http) 데이터 가져오기
wilson
2012. 3. 19. 13:32
반응형
JAVA 소스 에서 외부 HTTP의 내용을 가져올 경우가 있다.
이럴 경우에는 소스상에 openConnection을 이용해서 커넥션해서 정보를 가져오면 된다.
private String server ="http://www.test.co.kr/test.jsp"; private String userId = "?user_id="; private String userPw = "&user_passwd="; /** * useUrl * @Note : URL커넥션 사용 * @throws IOException * @throws Exception * * */ public void useUrl() throws IOException, Exception { String testVal = getReturnString( getUrlConnection() ); } /** * getUrlConnection * @Note : url 커넥션 * @return * @throws Exception * * */ public static URLConnection getUrlConnection( ) throws Exception { // URL 조합 String urlString = server + userId + "testId" + userPw + "testPw" ; URL url = new URL( urlString ); // 넘어오는 URL밎정보 URLConnection connection = url.openConnection(); // 커넥션 connection.setDoOutput( true ); return connection; } /** * getReturnString * @Note : 커넥션된 결과값 * @param connection * @return * @throws IOException * * */ public static String getReturnString( URLConnection connection ) throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream(), "UTF-8" ) ); // 반환되는 값이 UTF-8 경우 StringBuffer buffer = new StringBuffer(); String decodedString; while( ( decodedString = in.readLine() ) != null ) { buffer.append( decodedString ); } in.close(); return buffer.toString(); }
반응형