JAVA(STS)

[java] java network, URL로부터 얻은 정보 합치기 - StringBuilder

걍작 2022. 2. 6. 00:24

<웹페이지(URL)에 있는 조각난 정보를 한 줄로 합쳐보자>

- StringBuilder를 사용하여 JSP파일(URL)에 있는 조각난 데이터 값을 한줄로 합쳐보자

 

1.  대상 웹페이지(.jsp) 정보
>> 경로 : http://localhost:8090/jsp08rest/index2.jsp (로컬)
>> jsp페이지 코드 : 총 3줄의 데이터 값(kim/lee/park)과 데이터로 나열
kim
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<h1>lee</h1>
<h1>park</h1>​

>> jsp 웹화면 출력 결과 :

 

 

 

#Code

package test.com;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class test01Main_practice {

	public static void main(String[] args) {
		System.out.println("network...");

		// 특정 url로부터 정보를 얻는 방법
		String path = "http://localhost:8090/jsp08rest/index2.jsp";
		try {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			System.out.println(conn.getResponseCode());
			System.out.println(conn.getContentType());

			if (conn.getResponseCode() == 200) {
				BufferedReader br = new BufferedReader(
						new InputStreamReader(
								conn.getInputStream()));
				
				System.out.println("===readLine===");
				//제일 처음 한 줄 출력해줘 
				System.out.println(br.readLine());
				
				System.out.println("===StringBuilder===");
				//가져온 정보(readLine)값이 있다면 값을 받아서, StringBuilder로 값을 모아서 출력해줘 
				StringBuilder jsonText = new StringBuilder(); //StringBuilder는 객체를 생성해서 써야함
				String str = "";
				while ((str = br.readLine()) != null) {
					//System.out.println(str);
					jsonText.append(str);
				}
				System.out.println(jsonText.toString());;	
			}//end if

		} catch (MalformedURLException e) {
			System.out.println("MalformedURLException...");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("IOException...");
			e.printStackTrace();
		}

		System.out.println("end Main...");
	}// end main()

}

 

 

#결과값

1. System.out.println(br.readLine()); 을 통해 "kim"이 이미 출력됨.

2. jsonText.append(str); 을 통해 첫 줄을 제외한 나머지 "lee", "park"이 <합쳐져> 출력됨.

   (만약 앞의 readLine()이 없는 경우 kim부터 출력)

 

 

#추가 설명

1. 주석처리된 System.out.println(str);도 값을 모두 가져오나 한 줄씩 따로 가져오게 됨.

2. println과 append(StringBuilder) 모두 readLine 유무에 따라 읽어오는 첫 줄이 바뀜. >>(readLine이 2줄인 경우 3줄째부터 출력)