Programming > Java

Java 6 에서 HTTP POST ( 테스트용 ssl 무시 추가 샘플)

 

테스트용 샘플 코드

package com.emunhi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class Java6PostSample {

    public static void main(String[] args) {
        String apiUrl = "https://emunhi.com/service/api/hello";
        String params = "param1=value1&param2=value2";

        HttpURLConnection connection = null;
       
        sslTrust("emunhi.com");

        try {
            URL url = new URL(apiUrl);
            connection = (HttpURLConnection) url.openConnection();
           
            // POST
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            connection.setDoOutput(true);

            // Request
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(params);
            writer.flush();
            writer.close();

            // 응답 코드 확인
            int responseCode = connection.getResponseCode();
            System.out.println("응답: " + responseCode);

            if(responseCode == 200 ) {
                // 응답 데이터 읽기
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();
   
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
               
                // 결과 출력
                System.out.println("결과: " + response.toString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * SSL 인증서 신뢰 추가
     * @param domains
     */
    private static void sslTrust(final String... domains) {
        try {
            TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                    public void checkClientTrusted(X509Certificate[] certs, String authType) { }
                    public void checkServerTrusted(X509Certificate[] certs, String authType) { }
                }
            };
           
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            HostnameVerifier allHostsValid = new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    for(String domain: domains) {
                        if(domain.equals(hostname)) {
                            return true;
                        }
                    }
                    return false;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        } catch (Exception e) {
            // TODO : 실패시 필요한 조치
            e.printStackTrace();
        }
    }
}