JSON 파싱 연습

2024. 6. 7. 11:46·JAVA

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' 카테고리의 다른 글

람다식(Lambda expression)  (2) 2024.09.13
파싱이란 뭘까?(JSON 파싱 )  (0) 2024.06.07
(공부) 연결  (0) 2024.06.05
[JAVA] 네트워크 프로토콜  (0) 2024.05.24
[JAVA] 1: N 소켓 양방향 통신  (1) 2024.05.24
'JAVA' 카테고리의 다른 글
  • 람다식(Lambda expression)
  • 파싱이란 뭘까?(JSON 파싱 )
  • (공부) 연결
  • [JAVA] 네트워크 프로토콜
미로910
미로910
개발자를 꿈꾸는 민경이의 기록 블로그
  • 미로910
    개발 note
    미로910
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 설치 메뉴얼
      • HTML
      • JAVA
        • Java 기초
        • Java 응용
        • 자료구조
        • HTTP
        • JSP 프로그래밍
      • MySQL
        • MySQL 기본
        • 1일 1쿼리
      • CSS
      • Spring boot
      • JS
        • 게시판 만들기
      • Git
      • Flutter
        • MVVM 활용
        • 심화 버전
        • 1일 1 Flutter
      • 디자인 패턴의 활용
      • error note
      • My Project
        • [졸작] LLM 기반 특허 유사도 분석 시스템
        • 도서 관리 프로그램 (final project)
        • amigo
        • 친구 매칭 프로그램(FMP)
      • Python
      • 딥러닝
      • 네트워크
      • 공부 노트
        • 연구회
        • 자료구조
      • 기타
  • 블로그 메뉴

    • 홈
    • 전체보기
    • -----------------------
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Flutter
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
미로910
JSON 파싱 연습
상단으로

티스토리툴바