JAVA(STS)
[java] java network, 특정 URL로부터 정보를 얻어오는 방법 1 - 접근/읽어오기
걍작
2022. 2. 5. 17:53
<How to get information from a specific URL in java>
- java.net/java.io 패키지를 활용하여 데이터에 접근하고 데이터를 읽어오는 network를 구축해보자.
> 접근 : java.net.HttpURLConnection / java.net.MalformedURLException / java.net.URL
> 읽어오기 : java.io.BufferedReader / java.io.IOException / java.io.InputStreamReader
1. 해당 URL의 정보를 처리할 수 있는 서버
>> 프로젝트명 : jsp08rest (다이나믹웹프로젝트)
>> 경로 : http://localhost:8090/jsp08rest (로컬)
>> 서버 쪽 코드 2022.02.05 - [JAVA] - [java] jsp, json 웹페이지에 데이터 값 띄우기 1
#코드
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 {
public static void main(String[] args) {
System.out.println("network...");
// 특정 url로부터 정보를 얻는 방법
String path = "http://localhost:8090/jsp08rest/json_selectAll.do";
try {
URL url = new URL(path);
// Http 객체 타입으로 캐스팅 후 정보를 얻어오겠다(커넥션).
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
System.out.println(conn.getResponseCode());//연결 반응 코드 확인 (200-정상, 404 ...)
System.out.println(conn.getContentType());//가져오는 정보의 타입 확인(text, image..)
// 연결이 정상적(200)으로 되면,
if (conn.getResponseCode() == 200) {
BufferedReader br = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
//정보의 첫 줄(1줄)을 가져와서 콘솔에 출력해줘. (readLine()은 여러줄 못가져옴)
System.out.println(br.readLine());
}//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()
}
#결과값
next lesson > 2022.02.06 - [JAVA] - [java] java network, 특정 URL로부터 정보를 얻어오는 방법 2 - 데이터 값 배열 변경 및 객체화(org.json.jar download) / 파싱(parsing)