본문 바로가기

Programming/Java

[Interface] Google C2DM Sender


C2DMSender.java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Random;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import org.apache.log4j.Logger;

public class C2DMSender {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		C2DMSender c2dm = new C2DMSender();
		String strRegistrationId = "APA91bEeJhUerZCqu44neOSz9J06pvuJOQcPtEHdKuximfOpGdszTok353P_ETGARkBcOoZi2YxfiOFj5l3wZXZNevWHy7MMNMd8acuTKn2o6kfyxFYLWBUlEMNM6htqgkp3ZtHc6F7SNLMyBI50EoB5vQRjJeHvqQ";
		String strMessage = "테스트 메세지 입니다.";
		
		try {
			c2dm.sender(strRegistrationId, c2dm.getAuthToken(), strMessage);
		} catch ( Exception e ) {
			e.printStackTrace();
		}

	}
	
	protected final Logger logger = Logger.getLogger(getClass());
	
	private final String SenderID = "blog@javalove.co.kr";
	private final String SenderPassword = "javalove";
	private final String PackageName = "kr.co.javalove";
	
	public void sender(String registration_id, String authToken, String message) throws Exception {
		
		StringBuffer postDataBuilder = new StringBuffer();
		   
        /**
         * collapseKey를 랜던함게 생성한다.
         */
		Random random = new Random();
        int collapseKey = (random.nextInt(10) + 2) * (random.nextInt(10) + 10) + (random.nextInt(3) + 3);
        
		postDataBuilder.append("registration_id=" + registration_id); //등록ID
		postDataBuilder.append("&collapse_key=" + collapseKey); 
		postDataBuilder.append("&delay_while_idle=" + collapseKey);
		postDataBuilder.append("&data.msg=" + URLEncoder.encode(message, "UTF-8")); //태울 메시지

		byte[] postData = postDataBuilder.toString().getBytes("UTF8");
		
		URL url = new URL("https://android.apis.google.com/c2dm/send");
		
		HttpsURLConnection.setDefaultHostnameVerifier(new FakeHostnameVerifier());
		HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
		conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
		
		logger.debug("SEND : " + postDataBuilder.toString());
		
		OutputStream out = conn.getOutputStream();
		out.write(postData);
		out.close();

		logger.debug("RESPONSE : " + conn.getResponseMessage() + " [" + conn.getResponseCode() + "]");
		
		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

		String inputLine;
		String retMessage = "";
		while ((inputLine = in.readLine()) != null) {
			retMessage += inputLine;
		}
		
		logger.debug("RECEIVE : " + retMessage);
		
    }
	
    public String getAuthToken() throws Exception {
    	
    	String authtoken = "";
        
    	StringBuffer postDataBuilder = new StringBuffer();
        postDataBuilder.append("accountType=HOSTED_OR_GOOGLE"); 		// 고정
        postDataBuilder.append("&Email=" + SenderID);  					// 개발자 구글 ID
        postDataBuilder.append("&Passwd=" + SenderPassword);	        // 개발자 구글 비빌번호
        postDataBuilder.append("&service=ac2dm");						
        postDataBuilder.append("&source=" + PackageName);				// C2DM 신청 PackageName


        byte[] postData = postDataBuilder.toString().getBytes("UTF8");
        URL url = new URL("https://www.google.com/accounts/ClientLogin");
        
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
        
        OutputStream out = conn.getOutputStream();
        out.write(postData);
        out.close();


        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        
        String sidLine = br.readLine();
        String lsidLine = br.readLine();
        String authLine = br.readLine();
        
        logger.debug("SID : " + sidLine);
        logger.debug("LSID : " + lsidLine);
        logger.debug("AUTH : " + authLine);
        logger.debug("AUTHKEY : " + authLine.substring(5, authLine.length()));
        
        authtoken = authLine.substring(5, authLine.length());
        
        return authtoken;
        
    }
    
	// No subject alternative DNS name matching android.apis.google.com found.
	// 위의 error 관련
	private static class FakeHostnameVerifier implements HostnameVerifier {

		public boolean verify(String hostname, SSLSession session) {

			return true;

		}

	}

}