URL 내용 불러오기

[Java] Fake API 데이터 불러오기
Jan 12, 2024
URL 내용 불러오기

프로젝트 생성

notion image
File → New → Project 클릭
notion image
Name : myhttp
Language : Java
Build system : Gradle
Gradle DSL : Groovy
notion image
java에서
Package : com.metacoding.myhttp
Class : MyApp
 

Fake API 데이터로 예제 실습

Resources의 todos/1 주소 복사
 
아래와 같이 코드 작성
MyApp 클래스에
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class MyApp { public static void main(String[] args) { try { URL url = new URL("https://jsonplaceholder.typicode.com/todos/1"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // conn은 http 프로토콜이 적용된 소켓 BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream(),"UTF-8") ); String download = ""; while(true){ String line = br.readLine(); if(line == null) break; download = download + line; } System.out.println(download); } catch (Exception e) { throw new RuntimeException(e); } } }
실행 후 todo 데이터 확인
notion image
데이터
{ "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }
Share article
RSSPowered by inblog