HttpURLConnection

소만이·2024년 4월 1일
post-thumbnail

HttpURLConnection

: Java에서 HTTP를 통한 통신을 수행하기 위한 클래스이다. 이 클래스는 URL을 통해 HTTP서버와 통신하여 데이터를 요청하고 응답을 받는 데 사용된다. 당연히 GET, POST, PUT, DELETE 등의 요청을 보낼 수 있고 요청 헤더(header) 및 요청 본문(body)를 설정할 수 있으며, 서버로부터 받은 응답을 읽을 수 있다. 알아두어야 할 점은 HttpURLConnection을 사용할 때는 네트워크 통신 관련 예외를 항상 처리해야 한다는 것이다.

try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

		String username = "id";
		String password = "password";
		String authString = username + ":" + password;
		String encodedAuthString = Base64.getEncoder().encodeToString(authString.getBytes());
		// HttpURLConnection객체에 요청들 설정
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Authorization", "Basic " + encodedAuthString);

		connection.setRequestProperty("Accept-Charset", "UTF-8");
		connection.setRequestProperty("Accept", "application/json");
		connection.setRequestProperty("Content-Type", "application/json");
        
        //서버로부터 응답을 받기 위한 BufferedReader

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;

		// 응답을 읽어서 response에 저장
        //reader.readLine()을 사용하여 더 이상 읽어올 데이터가 없을 때까지 응답 데이터를 한 줄씩 읽어온다.
        while ((line = reader.readLine()) != null) {
           response.append(line);
        }

		reader.close();
		System.out.println("Response Body: " + response);

		//Gson 라이브러리를 사용하여 JSON의 응답 데이터를 Java 객체로 변환한다.
        //이를 위해 'fromJson' 메서드를 사용하고 변환할 클래스 타입을 지정한다.
        //여기서 변환할 클래스타입은 JiraData이다.
		Gson gson = new Gson();
		JiraData searchIssuesRes = gson.fromJson(response.toString(), JiraData.class);
        
     } catch (IOException e) {
         throw new RuntimeException("Second Catch", e);
     }

0개의 댓글