HttpURLConnection은 Java에서 HTTP 요청과 응답을 주고받기 위한 클래스입니다.URLConnection의 하위 클래스이며, REST API 호출에 자주 사용됩니다.URL url = new URL("https://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET"); // 또는 POST, PUT, DELETE 등
conn.setRequestProperty("Content-Type", "application/json");
int responseCode = conn.getResponseCode(); // 응답 코드 (200: 성공)
| 메서드 | 설명 |
|---|---|
setRequestMethod("GET") | 요청 방식 설정 |
setRequestProperty() | 요청 헤더 설정 |
getInputStream() | 응답 바디 읽기 |
getResponseCode() | HTTP 상태 코드 반환 |
disconnect() | 연결 종료 |
org.json.JSONObject는 JSON 객체를 표현하는 클래스입니다.String jsonStr = "{ \"name\": \"Inception\", \"year\": 2010 }";
JSONObject obj = new JSONObject(jsonStr);
String name = obj.getString("name");
int year = obj.getInt("year");
JSONObject 내부에서 또 다른 중첩된 JSON 객체를 가져올 때 사용합니다.{
"movie": {
"title": "Inception",
"year": 2010
}
}
JSONObject parent = new JSONObject(jsonStr);
JSONObject movie = parent.getJSONObject("movie");
String title = movie.getString("title"); // "Inception"
org.json.JSONArray는 JSON 배열을 표현하는 클래스입니다.{
"movies": [
{ "title": "Inception" },
{ "title": "Interstellar" }
]
}
JSONObject obj = new JSONObject(jsonStr);
JSONArray array = obj.getJSONArray("movies");
for (int i = 0; i < array.length(); i++) {
JSONObject movie = array.getJSONObject(i);
System.out.println(movie.getString("title"));
}
JSONArray 타입입니다.JSONArray movieList = jsonObject.getJSONArray("weeklyBoxOfficeList");
Jackson은 Java에서 JSON 데이터를 직렬화(Serialize) 또는 역직렬화(Deserialize) 할 수 있도록 도와주는 강력한 라이브러리입니다.
POJO 기반 (Plain Old Java Object)Lombok, Spring Boot과 완벽 호환Map, List, Generic, Date, LocalDate, Enum 등 다양한 타입 자동 지원public class Movie {
public String title;
public int year;
}
Movie movie = new Movie();
movie.title = "Inception";
movie.year = 2010;
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(movie);
System.out.println(json);
{"title":"Inception","year":2010}
String json = "{\"title\":\"Interstellar\",\"year\":2014}";
Movie movie = mapper.readValue(json, Movie.class);
| 어노테이션 | 설명 |
|---|---|
@JsonProperty("json이름") | JSON 속성과 Java 필드 이름 매핑 |
@JsonIgnore | 해당 필드 무시 |
@JsonIgnoreProperties(ignoreUnknown = true) | 모르는 JSON 속성 무시 |
@JsonFormat | 날짜/시간 포맷 지정 |
@JsonInclude | null 등 제외 조건 지정 |
@JsonAlias({"이름1", "이름2"}) | 여러 JSON 키를 한 필드에 매핑 |
JSON 필드 이름과 Java 필드 이름이 다를 때 매핑
public class User {
@JsonProperty("user_name")
private String username;
@JsonProperty("user_age")
private int age;
}
알 수 없는 JSON 필드가 들어와도 무시하고 예외를 발생시키지 않음
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
private String name;
}
날짜, 시간 형식을 지정해서 문자열 ↔ 객체 간 변환 제어
public class Event {
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate eventDate;
}
특정 조건에 따라 필드를 JSON에 포함시킬지 결정
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
private String name;
private String nickname; // null이면 출력 안 됨
}
JSON에서 여러 키 이름을 같은 필드로 매핑
public class User {
@JsonAlias({"user_name", "username", "name"})
private String username;
}
public class User {
private final String name;
private final int age;
@JsonCreator
public User(@JsonProperty("user_name") String name,
@JsonProperty("user_age") int age) {
this.name = name;
this.age = age;
}
}
Jsoup = Java + HTML Parser
document.select("div.title"))Jsoup.connect("url"))String html = "<html><body><h1>Hello Jsoup</h1></body></html>";
Document doc = Jsoup.parse(html);
String text = doc.select("h1").text(); // "Hello Jsoup"
System.out.println(text);
Document doc = Jsoup.connect("https://example.com").get();
String title = doc.title();
System.out.println("페이지 제목: " + title);
Elements newsHeadlines = doc.select("#news .headline a");
for (Element headline : newsHeadlines) {
System.out.println(headline.text());
System.out.println(headline.attr("href"));
}
Element link = doc.select("a").first();
String text = link.text(); // 링크의 텍스트
String href = link.attr("href"); // 링크의 주소
| 클래스 | 설명 |
|---|---|
Jsoup | HTML을 가져오거나 파싱하는 정적 메서드 제공 |
Document | HTML 전체 문서 표현 (DOM 트리) |
Elements | 여러 Element의 리스트 (select() 결과) |
Element | HTML 태그 하나 (<div>, <a> 등) |
public class NewsCrawler {
public static void main(String[] args) throws IOException {
Document doc = Jsoup.connect("https://news.google.com/topstories?hl=ko&gl=KR&ceid=KR:ko").get();
Elements headlines = doc.select("article h3");
for (Element h : headlines) {
System.out.println(h.text());
}
}
}
robots.txt를 반드시 준수하세요User-Agent, Timeout, Proxy 등 설정도 가능Jsoup.connect("https://example.com")
.userAgent("Mozilla/5.0")
.timeout(3000)
.get();
Reference