본문 바로가기
개발/Java

[HttpsUrlConnection] 인증서 GET/POST JSON 통신

by 코딩하는 흰둥이 2023. 5. 6.
반응형

Http 가 아닌 Https 다 

회사에서 사용하는 인증서가 따로 있어서 인증서 생성하는 과정은 생략 했다

Get 방식
package com.example.practice.controller;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

public class RunTestController {
    public static void main(String[] args) throws Exception {

        String urlString = "https://www.google.com";

        String line = null;
        InputStream in = null;
        BufferedReader reader = null;
        HttpsURLConnection httpsConn = null;

        try {
            // Get HTTPS URL connection
            URL url = new URL(urlString);
            httpsConn = (HttpsURLConnection) url.openConnection();


            // Set Hostname verification
            httpsConn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    // Ignore host name verification. It always returns true.
                    return true;
                }
            });

            // Input setting
            httpsConn.setDoInput(true);
            // Caches setting
            httpsConn.setUseCaches(false);
            // Read Timeout Setting
            httpsConn.setReadTimeout(1000);
            // Connection Timeout setting
            httpsConn.setConnectTimeout(1000);
            // Method Setting(GET/POST)
            httpsConn.setRequestMethod("GET");
            // Header Setting
            httpsConn.setRequestProperty("HeaderKey","HeaderValue");


            int responseCode = httpsConn.getResponseCode();
            System.out.println("응답코드 : " + responseCode);
            System.out.println("응답메세지 : " + httpsConn.getResponseMessage());

            // SSL setting
            SSLContext context = SSLContext.getInstance("TLS");
            // init에 모두 null 을 넣어서 인증과정을 무시하고 서버의 내용물을 받음
            context.init(null, null, null);
            httpsConn.setSSLSocketFactory(context.getSocketFactory());

            // Connect to host
            httpsConn.connect();
            httpsConn.setInstanceFollowRedirects(true);

            // Print response from host
            if (responseCode == HttpsURLConnection.HTTP_OK) { // 정상 호출 200
                in = httpsConn.getInputStream();
            } else { // 에러 발생
                in = httpsConn.getErrorStream();
            }
            reader = new BufferedReader(new InputStreamReader(in , "UTF-8"));



            while ((line = reader.readLine()) != null) {
                System.out.printf("%s\n", line);
            }
            reader.close();
        } catch (UnknownHostException e) {
            System.out.println("UnknownHostException : " + e);
        } catch (MalformedURLException e) {         // 받은 url 문자열이 null 이거나 문제가 있을때 발생
            System.out.println(urlString + " : "+ e);
        } catch (IOException e) {
            System.out.println("IOException : " + e);
        } catch (Exception e) {
            System.out.println("error : " + e);
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (httpsConn != null) {
                httpsConn.disconnect();
            }
        }
    }
}

 

 

 

Post 방식
package com.example.practice.controller;

import org.json.JSONObject;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

public class RunTestController {
    public static void main(String[] args) throws Exception {

        String urlString = "https://www.google.com";

        String line = null;
        InputStream in = null;
        BufferedReader reader = null;
        HttpsURLConnection httpsConn = null;

        try {
            URL url = new URL(urlString);
            httpsConn = (HttpsURLConnection) url.openConnection();


            // Set Hostname verification
            httpsConn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            // Input setting
            httpsConn.setDoInput(true);
            // Output setting
            httpsConn.setDoOutput(true);
            // Caches setting
            httpsConn.setUseCaches(false);
            // Read Timeout Setting
            httpsConn.setReadTimeout(1000);
            // Connection Timeout setting
            httpsConn.setConnectTimeout(1000);
            // Method Setting(GET/POST)
            httpsConn.setRequestMethod("POST");
            // Header Setting
            httpsConn.setRequestProperty("Content-type", "application/json");
            httpsConn.setRequestProperty("Accept", "application/json");



            /**
             * JSON URL 전송 예)
             */
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", "abc");
            jsonObject.put("password", "1234");

            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(httpsConn.getOutputStream()));

            bw.write(jsonObject.toString(4));
            bw.flush();
            bw.close();

            System.err.println(jsonObject.toString(4));

            int responseCode = httpsConn.getResponseCode();
            System.out.println("응답코드 : " + responseCode);
            System.out.println("응답메세지 : " + httpsConn.getResponseMessage());

            // SSL setting
            SSLContext context = SSLContext.getInstance("TLS");
            // init에 모두 null 을 넣어서 인증과정을 무시하고 서버의 내용물을 받음
            context.init(null, null, null);
            httpsConn.setSSLSocketFactory(context.getSocketFactory());

            // Connect to host
            httpsConn.connect();
            httpsConn.setInstanceFollowRedirects(true);

            // Print response from host
            if (responseCode == HttpsURLConnection.HTTP_OK) { // 정상 호출 200
                in = httpsConn.getInputStream();
            } else { // 에러 발생
                in = httpsConn.getErrorStream();
            }
            reader = new BufferedReader(new InputStreamReader(in , "UTF-8"));

            while ((line = reader.readLine()) != null) {
                System.out.printf("%s\n", line);
            }
            reader.close();
        } catch (UnknownHostException e) {
            System.out.println("UnknownHostException : " + e);
        } catch (MalformedURLException e) {         // 받은 url 문자열이 null 이거나 문제가 있을때 발생
            System.out.println(urlString + " : "+ e);
        } catch (IOException e) {
            System.out.println("IOException : " + e);
        } catch (Exception e) {
            System.out.println("error : " + e);
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (httpsConn != null) {
                httpsConn.disconnect();
            }
        }

    }
}

댓글