반응형
자바로 HttpsURLConnection을 사용하여 https 사이트에 connect 하면 오류가 난다.

이 경우에는 SSL을 무시하여 우회하도록 하는 코드를 작성하여야 한다.

먼저, 해당 URL이 https 인지 판별하는 코드를 썼다.

1
2
3
4
5
6
URL aURL = new URL(url);
 
if (aURL.getProtocol().equals("https")) {    //해당 url이 https이면
      resultData = httpsGet(url);            //ssl인증서를 무시하는 함수를 호출한다.
      logger.debug("https resultData: {}" , resultData);
}
cs


httpsGet함수 - 다른 부분은 http 호출방식과 유사하나 ignoreSSL 처럼 connection 전에 처리해줘야할 사항들이 있다.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    public static String httpsGet(String strURL) throws Exception
    {
        URL url = null;
        HttpsURLConnection con = null;
        String ret = new String();
        
        try {
            url = new URL(strURL);
            ignoreSsl();
            con = (HttpsURLConnection)url.openConnection();
    
    
            BufferedReader br = null;
            br = new BufferedReader(new InputStreamReader(con.getInputStream()));
    
            String input = null;
    
            while ((input = br.readLine()) != null){
                ret += input;
            }
            
            br.close();
        }
        catch (IOException e) {
            ExceptionUtil.getStackTrace(e);
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        
        return ret;
        
    }
cs


ignoressl()함수
1
2
3
4
5
6
7
8
9
    public static void ignoreSsl() throws Exception{
        HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) 
                return true;
            }
        };
        trustAllHttpsCertificates();
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
    private static void trustAllHttpsCertificates() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[1];
        TrustManager tm = new miTM();
        trustAllCerts[0= tm;
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }
 
    static class miTM implements TrustManager,X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
 
        public boolean isServerTrusted(X509Certificate[] certs) {
            return true;
        }
 
        public boolean isClientTrusted(X509Certificate[] certs) {
            return true;
        }
 
        public void checkServerTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
            return;
        }
 
        public void checkClientTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
            return;
        }
    }
cs



핵심은 connection 전에 호출 처리를 해줘야 오류가 나지 않는다.


반응형
반응형
String
String은 새로운 값을 할당할 때마다 새로 생성된다.
char형의 배열형태로 저장되며 final형이기 때문에 초기값으로 주어진 String의 값은 불변으로 바꿀 수가 없게 되는 것이다.

StringBuilder, StringBuffer

둘 다 객체의 공간이 부족해지면 기존의 버퍼 크기를 늘리면서 유연하게 동작한다.

StringBuffer는 멀티스레드 환경에서의 동기화를 지원하지만 StringBuilder는 단일스레드 환경에서만 동기화를 지원한다. 물론 단일스레드 환경에서 StringBuffer를 사용해서 문제가 되는 것은 아니지만 동기화와 관련된 처리로 인해 StringBuilder에 비해 성능이 좋지 않다.

StringBuffer는 각 메서드별로 Synchronized Keyword가 존재하여, 멀티스레드 환경에서도 동기화를 지원.


※ JDK 1.5 버전 이후에는 String 객체를 사용하더라도 컴파일 단계에서 StringBuilder로 컴파일되도록 변경되었다. 따라서 일반적으로 String 클래스를 활용해도 StringBuilder와 성능상으로 차이가 없다고 한다.


하지만 반복 루프를 사용해서 문자열을 더할 때에는 객체를 계속 추가한다는 사실에는 변함이 없습니다. 그러므로 String 클래스를 쓰는 대신, 스레드와 관련이 있으면 StringBuffer를, 스레드 안전 여부와 상관이 없으면 StringBuilder를 사용하는 것을 권장합니다.

 

단순히 성능만 놓고 본다면 연산이 많은 경우, StringBuilder > StringBuffer >>> String 입니다.


검색을 통하여

출처: http://12bme.tistory.com/42 [길은 가면, 뒤에 있다]


반응형

+ Recent posts