2013년 12월 5일 목요일

Apache HttpClient를 사용하여 Https 요청하기

이 글은 HttpClient 4.2.5 버전을 기준으로 작성되었으며, 4.3.x 버전에서는 SSLSocketFactory가 deprecated 되었고, 대신 SSLConnectionSocketFactory를 사용하기를 권고하고 있다.

GCM(Google Cloud Messaging)을 사용하려다 보니, 요청을 https로 처리해야 해서 정리를 하게 되었다. 여기서는 인증서를 검증(verify)하지 않고 모든 인증서를 허용하는 로직을 사용한다.
 

           SSLContext sslContext = SSLContext.getInstance("TLS"); 
           // 모든 인증서를 허용한다  
           TrustManager tm = new X509TrustManager()  
           {  
                @Override  
                public X509Certificate[] getAcceptedIssuers()  
                {  
                     return null;  
                }  
                @Override  
                public void checkServerTrusted(X509Certificate[] cetificates, String authType) throws CertificateException  
                {  
                }  
                @Override  
                public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException  
                {  
                }  
           };  
           sslContext.init(null, new TrustManager[]{ tm }, new SecureRandom()); 
           SSLSocketFactory sf = new SSLSocketFactory(sslContext);

           // https scheme을 등록하면서, 위에서 생성한 SSLSocketFactory를 객체를 사용한다         
           SchemeRegistry schemeRegistry = new SchemeRegistry();  
           schemeRegistry.register(new Scheme("https", 443, sf));
  
           // GCM에 POST 요청을 보낸다
           ClientConnectionManager cm = new BasicClientConnectionManager();  
           HttpClient httpClient = new DefaultHttpClient(cm);  
           HttpPost post = new HttpPost("https://android.googleapis.com/gcm/send");  
           post.addHeader("Content-Type", "application/json");  
           post.addHeader("Authorization", "key=A");  
           post.setEntity(new StringEntity("{ \"registration_ids\": [ \"42\" ] }"));  
           HttpResponse response = httpClient.execute(post);  
           HttpEntity entity = response.getEntity();  
           BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));  
           String line = null;  
           while ((line = br.readLine()) != null) {  
                System.out.println(line);  
           }  
           br.close();  

댓글 없음:

댓글 쓰기