fcm push notification example / send post request to fcm api java sample / fcm api post 호출 자바 샘플

북마크 추가

push notification 전송을 위해 firebase cloud console api를 호출 하는 방법 중

 

자바 서버에서 호출 하는 방법입니다.

 

1. function sendPost() 작성

 

public String sendPost(String url, String parameters) throws Exception { 
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
public X509Certificate[] getAcceptedIssuers(){return new X509Certificate[0];}
public void checkClientTrusted(X509Certificate[] certs, String authType){}
public void checkServerTrusted(X509Certificate[] certs, String authType){}
}};
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

//reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "key=Firebase API KEY");
String urlParameters = parameters;

//post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(urlParameters.getBytes("UTF-8"));
wr.flush();
wr.close();

int responseCode = con.getResponseCode();
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);

StringBuffer response = new StringBuffer();

if(responseCode == 200){
BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
}
//result
System.out.println(response.toString());
return response.toString();
}

 

2. 사용방법

 

String url = "https://fcm.googleapis.com/fcm/send"; 

 

String parameters = "{"+

"\"data\": {"+

"\"message\": {" +

"\"title\": \"test\","+

"\"content\": \"test content\","+

"\"imgUrl\": \"\","+

"\"link\": \"\","+

"}"

                "},"+

"\"to\": "\"/topics/noticeMsg\""+

"}"; 

String result = sendPost(url,parameters);

 

 ->  "{\"data\" : {\"message\" : {\"title\":\"test\",\"content\":\"test content\",\"imgUrl\":\"\",\"link\":\"\"}},\"to\" : \"/topics/noticeMsg\"}";


 

 

 

 

 

 

 

AD
관리자
2017-02-28 16:43
SHARE
댓글

2번 사용방법에 타이틀, 콘텐츠가 제목과 내용이고 이미지를 보내면 내용 대신에 이미지를 띄워줄 수  있습니다.
앱 내에 데이터 수신하여 푸쉬알림으로 보여줄수있도록 작업이 필요하고 내용은 앞에 있습니다
H**

sendPost()를 호출하면 어떤 내용이 푸쉬되죠? 그 푸쉬 내용을 앱 내에서 정할수 있을까요?
김**

푸시알림을 보내고자 하는  시점에 sendPost(url,parameters); 를 호출하면 푸시알림이 발송됩니다
H**

1.은 sendPost()를 말하는거고 2.는 sendPost를 호출하는겁니다
H**

말씀해주신 '저건'  이것이 어떤것을 칭하는 것이죠..?? function sendPost() 를 말씀하시는건가요??

2.사용방법 이부분은 어디서 사용을 하는건가요??
k***

저건 안드로이드쪽 푸시수신쪽이 아니라 발신하는쪽입니다. 푸시를 보낼 서버쪽에 작성하면됩니다
 웹에서 발신한다고 가정했을때 컨트롤러나 서비스 자바클래스에 만들면 될듯합니다
S***

안녕하세요 글을 읽다가 궁금한점이 생겨서 질문드립니다..
function sendPost()는 자바 클래스를 만들어서 작성해줘야하나요??  사용할쪽에다가 저 코드를 작성해줘야하나요??ㅠㅠ
사용방법이라고 되있는 코드는 어떻게 사용하는것인가요...ㅠㅠ
안드로이드스튜디오 사용하고있습니다
k***

php에서 json으로 전송시 아래처럼 array에 넣고 json_encode로 날리고요

$data = array(
		"to"=>$to,
		"data"=>array(
					"title"=>"제목",
					"message"=>$message,
					"imgUrl"=>"http://~~",
					"link"=>"http://~~"
		)
	);

json_encode($data)



받을 때는 이런식으로 뽑으면 됩니다.
sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("message"), remoteMessage.getData().get("imgUrl"));
김**

스프링에서 클래스 만들어서 써주시면 됩니다
H**

안녕하세요 안드로이드 초보개발자인데요... 인스타그램을 모티브로 프로젝트 준비하는중인데
저 자바문은 스튜디오에 자바클래스만들어서 써주는건가요?
저희팀은 스프링프레임워크로 서버 구현해놔서 헷갈리네요 ㅠㅠ
홍*

https://trandent.com/board/Android/detail/739 글에서 
5. FirebaseMessagingService.java 내용중
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
.
.
.
.setSound() 

로 되어있는 부분이 사운드 설정입니다. 사운드설정만 해놓으면 진동은 매너모드일때 알아서 옵니다
H**

디바이스에서 푸시를 받을때 소리나 진동이 나게 하려면 뭘 추가해야 할까요?
또***