상세 컨텐츠

본문 제목

JSON 파싱 연습

JAVA

by 미로910 2024. 6. 7. 11:46

본문

https://jsonplaceholder.typicode.com/

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake and reliable API for testing and prototyping. Powered by JSON Server + LowDB. Serving ~3 billion requests each month.

jsonplaceholder.typicode.com



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

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class MyHttpAlbumClient {

	public static void main(String[] args) {

		// 순수 자바코드에서 HTTP 통신
		// 1. 서버 주소 경로
		// 2. URL 클래스
		// 3. url.openConnection() <--- 스트림 I/O

		try {
			URL url = new URL("https://jsonplaceholder.typicode.com/albums/1");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Content-type", "application/json");

			// 응답 코드 확인
			int respinseCode = conn.getResponseCode();
			System.out.println("response code : " + respinseCode);

			// HTTP 응답 메세지에 데이터를 추출 [] ---Stream--- []
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String inputLine;
			StringBuffer buffer = new StringBuffer();
			while ((inputLine = in.readLine()) != null) {
				buffer.append(inputLine);
			}
			in.close();

			System.out.println(buffer.toString());
			System.out.println("-------------------");
			// gson lib 활용
			// Gson gson = new Gson();
			Gson gson = new GsonBuilder().setPrettyPrinting().create();
			Album albumDTO = gson.fromJson(buffer.toString(), Album.class);

			System.out.println(albumDTO.getId());
			System.out.println(albumDTO.getUserId());
			System.out.println(albumDTO.getTitle());

		} catch (IOException e) {
			e.printStackTrace();
		}

	}// end of main

}// end of class

실행 결과________

'JAVA' 카테고리의 다른 글

파싱이란 뭘까?(JSON 파싱 )  (0) 2024.06.07
(공부) 연결  (0) 2024.06.05
[JAVA] 네트워크 프로토콜  (0) 2024.05.24
[JAVA] 1: N 소켓 양방향 통신  (1) 2024.05.24
[JAVA] 1:1 양방향 통신(채팅 기본 기능 구현)  (0) 2024.05.24

관련글 더보기