The Kahimyang Project Logo
Primo's Code Blog
Howtos tips and tricks
The Kahimyang Project

How to get Google +1 pluses count in Java

Here is a simple way to manually get the Google +1 pluses count for your web pages using Java. This is based on a PHP implementation from this blog post.

Google +1 API pluses count is available through the following endpoint:

https://clients6.google.com/rpc?
	key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ

The service is a JSON RPC setup which requires a POST request using JSON data with the following format. Just supply the URL of the target page replacing the PAGE_URL in the sample below.

[
{"method":
        "pos.plusones.get",
	"id":"p",
	"params":{"nolog":true,"id":"PAGE_URL",
            "source":"widget",
            "userId":"@viewer",
            "groupId":"@self"},
	"jsonrpc":"2.0","key":"p","apiVersion":"v1"
}
]

The response should look like the following:

[
{"result": 
    { "kind": "pos#plusones", 
        "id": "PAGE_URL", 
        "isSetByViewer": false, 
        "metadata": 
            {"type": "URL", 
		"globalCounts": {"count": 51.0} 
            } 
    } "id": "p"
}
]

The Java Code

Below is how we implemented the request and extract the count from JSON data in Java.

public String plusCount(String pageUrl) {

    String plusCount = "-1";

    StringBuilder postData =
            new StringBuilder("{\"method\":\"pos.plusones.get\",");
    postData.append("\"id\":\"p\",");
    postData.append("\"params\":");
    postData.append("{\"nolog\":true,");
    postData.append("\"id\":\"");
    postData.append(pageUrl);
    postData.append("\",");
    postData.append("\"source\":\"widget\",");
    postData.append("\"userId\":\"@viewer\",");
    postData.append("\"groupId":\"@self\"");
    postData.append("},");
    postData.append("\"jsonrpc\":\"2.0\",");
    postData.append("\"key\":\"p\",");
    postData.append("\"apiVersion\":\"v1\"}");

    StringBuilder response = new StringBuilder();

    try {
        URL url = new URL("https://clients6.google.com/rpc?"
                + "key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ");

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.addRequestProperty("User-Agent", "Mozilla");
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("POST");

        connection.addRequestProperty("Content-Length", "" + postData.length());
        connection.setDoOutput(true);
        connection.setDoInput(true);

        DataOutputStream outputStream = new DataOutputStream(
                connection.getOutputStream());
        outputStream.writeBytes(postData.toString());

        outputStream.flush();
        outputStream.close();

        InputStream input = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));

        String line;

        while ((line = reader.readLine()) != null) {
            response.append(line);
        }

        reader.close();

    } catch (IOException e) {
        return plusCount;
    }

    try {

        Gson gs = new Gson();
        Map<String, Map<String, Object>> map = new HashMap();
        map = gs.fromJson(response.toString(), map.getClass());
        
        if (map != null) {
            Map<String, Object> result = (Map<String, Object>) map.get("result");
            Map<String, Object> metaData = (Map<String, Object>) result.get("metadata");
            if (metaData != null) {
                Map<String, Object> globalCounts =
                        (Map<String, Object>) metaData.get("globalCounts");
                if (globalCounts != null) {
                    Double C = (Double) globalCounts.get("count");
                    plusCount = "" + C.intValue();
                }
            }
        }

    } catch (Exception e) {
        return "-1";
    }

    return plusCount;
}

That's it, good luck.

RSS Logo



Comment icon   Comments (Newest first)

Recent posts in Java/JSF category
Blue dot icon Using Rhinoslider with image and youtube content in JSF pages
Blue dot icon A dynamic standard sitemap.xml with Google image extension implemented as a Java Servlet
Blue dot icon Creating a Facebook-like panel with slim scrollbars and infinite scrolling in PrimeFaces
Blue dot icon Generating XML RSS 2 feeds with JDOM 2 with a servlet
Blue dot icon Building a page with infinite scroll in PrimeFaces using Waypoints jQuery plugin
Blue dot icon Implementing a collapsible ui:repeat rows in JSF
Blue dot icon Validating an email address in PrimeFaces p:inputText field with p:ajax





Most popular articles
Blue dot icon Using Expect script to automate SSH logins and do routine tasks accross multiple hosts   (15318)
Blue dot icon How to setup Tomcat 7 as your primary webserver on Debian Squeeze    (14061)
Blue dot icon How to setup FLV streaming with crtmpserver C++ RTMP server   (9813)
Blue dot icon A Java class for sending multipart Email messages through your Gmail account    (6970)
Blue dot icon How to use Google Translate's Text to Speech (TTS) services in your web page using Servlet   (5660)
Blue dot icon Speed up Primefaces page load with p:remoteCommand partial update   (5436)
Blue dot icon Building a mobile website with JSF 2 core and JQuery Mobile 1.0   (5316)
Blue dot icon Google Map-Adding markers, info window, circle, small control, and events in Javascript    (5215)