Etc..

JAVA HttpURLConnection

공기팝님 2024. 6. 15. 18:22
반응형
public class BankingAppApplication {

   public static void main(String[] args) throws IOException {
      SpringApplication.run(BankingAppApplication.class, args);

      //getAPIMethod();
        postAPIMethod();
   }

   private static void postAPIMethod() {
      try {
         // 요청할 URL 설정
         URL url = new URL("http://localhost:8080/api/accounts");
         HttpURLConnection con = (HttpURLConnection) url.openConnection();
         showInfo(url);
         // HTTP 요청 설정
         con.setRequestMethod("POST");
         con.setRequestProperty("Content-Type", "application/json");
         con.setRequestProperty("Accept", "application/json");
         con.setRequestProperty("x-api-key", "testKey111");
         con.setDoOutput(true);

         Account account = new Account();
         account.setAccountHolderName("jiin");
         account.setBalance(5000);

         // Map을 JSON 문자열로 변환
         Gson gson = new Gson();
         String jsonData = gson.toJson(account);

         OutputStream os  = con.getOutputStream();
         OutputStreamWriter osw  = new OutputStreamWriter(os, StandardCharsets.UTF_8);
         osw.write(jsonData);

         osw.flush();
         osw.close();

         // 응답 코드 확인
         System.out.println("getContentType():" + con.getContentType()); // 응답 콘텐츠 유형 구하기
         System.out.println("getResponseCode():"    + con.getResponseCode()); // 응답 코드 구하기
         System.out.println("getResponseMessage():" + con.getResponseMessage()); // 응답 메시지 구하기

         // 연결 해제
         con.disconnect();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }


   private static void getAPIMethod() throws IOException {
      try {
         URL url = new URL("http://localhost:8080/api/accounts/2");
         showInfo(url);
         HttpURLConnection con= (HttpURLConnection)url.openConnection();
            con.setRequestMethod("GET");
         con.setRequestProperty("Accept", "application/json");
         con.setRequestProperty("x-api-key","testKey111");

          System.out.println("getContentType():" + con.getContentType()); // 응답 콘텐츠 유형 구하기
          System.out.println("getResponseCode():"    + con.getResponseCode()); // 응답 코드 구하기
          System.out.println("getResponseMessage():" + con.getResponseMessage()); // 응답 메시지 구하기

           System.out.println("..........................");
           //InputStreamReader inputStreamReader = new InputStreamReader(con.getInputStream()); //InputStreamReader는 바이트 스트림에서 문자 스트림으로의 브리지입니다.

           // 응답 데이터 읽기
          BufferedReader re = new BufferedReader(new InputStreamReader(con.getInputStream()));

         String line;
         StringBuilder sb = new StringBuilder();
         while ((line = re.readLine()) != null) {
            sb.append(line).append("\n");
         }
         System.out.println("" + sb.toString());
         re.close();
         con.disconnect();
      } catch (MalformedURLException e) {
         throw new RuntimeException(e);
      }
   }

   private static void showInfo(URL url) {
      System.out.println("Protocol : " + url.getProtocol());
      System.out.println("Host Name :" + url.getHost());
      System.out.println("Port Number :" +  url.getPort());
      System.out.println("file Name :" + url.getFile());
      System.out.println("getPath :" + url.getPath());
      System.out.println("getQuery:" + url.getQuery());
   }
반응형