티스토리 뷰

반응형

GCM iOS Push 보내기!


String apiKey = ""; // 발급받은 kEY   

String GCM_Token = regId; // Registration ID

// Json 데이터 세팅

String notification = "{\"sound\":\"default\",\"badge\":\"2\",\"title\":\"\",\"body\":\""+ contents +"\"}";

String contentsData  = "{\"원하는데이터\":\""+원하는데이터"}";

String messageToSend = "{\"to\":\"" + GCM_Token + "\",\"notification\":" + notification + ",\"data\":" + contentsData + "}";

try {

// URL

URL url = new URL("https://android.googleapis.com/gcm/send");


System.out.println(messageToSend);

// Open connection

HttpURLConnection conn = (HttpURLConnection) url.openConnection();


// Specify POST method

conn.setRequestMethod("POST");


//Set the headers

conn.setRequestProperty("Content-Type", "application/json");

conn.setRequestProperty("Authorization", "key=" + apiKey);

conn.setDoOutput(true);


//Get connection output stream

DataOutputStream wr = new DataOutputStream(conn.getOutputStream());


byte[] data = messageToSend.getBytes("UTF-8");

wr.write(data);


//Send the request and close

wr.flush();

wr.close();


//Get the response

int responseCode = conn.getResponseCode();

//System.out.println("\nSending 'POST' request to URL : " + url);

   // System.out.println("Response Code : " + responseCode);


BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

String inputLine;

StringBuffer response = new StringBuffer();


while ((inputLine = in.readLine()) != null) {

response.append(inputLine);

}

in.close();

JSONParser jsonParser = new JSONParser();

JSONObject jsonObj = (JSONObject) jsonParser.parse(response.toString());

JSONObject sendResult = (JSONObject) jsonObj;

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}


위 코드는 상용에서 사용하고 있는 코드이며 기존 Android Push기능을 GCM을 통해 수행하고 있었으며, iOS Push 기능을 추가 함



끗!!!!!!



반응형