Using Facebook API to send notifications to user in Java

We often get notifications on Facebook. Some of them are Facebook specific and some are sent by Facebook applications. Only those applications which you would have used have the authorization of sending you notifications.

So here is the code to send Facebook notification in Java. We need to hit “/notifications” endpoint of Facebook API.
at‘ is the access token you would have got after user’s Facebook login. ‘u1‘ is userid of the user whom you want to send the notification to. ‘template‘ is the text message you want to send and ‘href‘ is the link where user will be redirected to once he clicks on the notification

public static void sendNotification(String at, String template, String u1,
			String href) {
 
		String query = "access_token=" + at + "&template=" + template;
		if (null != href)
			query = query + "&href=" + href;
		BufferedReader br = null;
		try {
			URL url = new URL("https://graph.facebook.com/" + u1
					+ "/notifications");
 
			HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
			urlc.setRequestMethod("POST");
			urlc.setDoOutput(true);
			urlc.setAllowUserInteraction(false);
			PrintStream ps = new PrintStream(urlc.getOutputStream());
 
			ps.print(query);
			ps.close();
			br = new BufferedReader(
					new InputStreamReader(urlc.getInputStream()));
			String l = null;
			while ((l = br.readLine()) != null) {
                           System.out.println(l);	
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != br) {
					br.close();
				}
 
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
 
	}

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *