Java GCM 샘플 코드

java 2014.03.17 18:39

Spring Rest Template 를 활용한 GCM 커넥터 샘플 코드

코드 포인트

 1. Interface부를 따로 분리하지 않음.

 2. RestTemplate 를 활용

 3. GCM 전송


@Component

@Scope("singleton")

public class GcmConnector {


    private Logger logger = LoggerFactory.getLogger(getClass());


    @Value("${google.gcm.url}")

    private String googleGcmUrl;

    @Value("${google.gcm.authToken}")

    private String googleGcmAuthToken;


    public boolean sendMessage(String registrationId, String message) throws Exception {

        StringBuffer postDataBuilder = new StringBuffer();

        postDataBuilder.append("registration_id=" + registrationId); // 등록ID 

        postDataBuilder.append("&collapse_key=1");

        postDataBuilder.append("&delay_while_idle=1");

        try {

            postDataBuilder.append("&data.msg=" + URLEncoder.encode(message, "UTF-8")); //msg


            UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(googleGcmUrl);


            HttpHeaders httpHeaders = new HttpHeaders();

            httpHeaders.add(org.apache.http.HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8");

            httpHeaders.add(org.apache.http.HttpHeaders.CONTENT_LENGTH, String.valueOf(postDataBuilder.length()));

            httpHeaders.add(org.apache.http.HttpHeaders.AUTHORIZATION, "key=" + googleGcmAuthToken);

            HttpEntity<String> httpEntity = new HttpEntity<String>(postDataBuilder.toString(), httpHeaders);


            new RestTemplate().exchange(uriComponentsBuilder.build().toUri(), HttpMethod.POST, httpEntity, String.class);

            return true;

        } catch (UnsupportedEncodingException e) {

            logger.error("GcmPushConnectorImpl pushRestTemplate faild. cause : " + e.getMessage());

        } catch (HttpClientErrorException e) {

            logger.error("GcmPushConnectorImpl pushRestTemplate faild. cause : " + e.getMessage());

        }

    }

}



'java' 카테고리의 다른 글

abstract 와 interface 차이  (0) 2014.03.26
객체를 인자로 보내서 값을 설정하는것  (0) 2014.03.18
Java GCM 샘플 코드  (0) 2014.03.17
jaxb sample code  (0) 2014.03.17
GCM MismatchSenderId  (0) 2014.03.12
xmpp sasl authentication digest-md5 failed not-authorized  (0) 2014.03.04
블로그 이미지

기계새

Java, Spring, iBatis, Maven, eclipse 개발관련 잡다한 메모공간입니다.

댓글을 달아 주세요