Tuesday, November 30, 2010

Integrating Delicious Search in your application with java

Delicious provides us facility to search public and private bookmarks/results with the help of a particular tag, url, & etc...... for publicly accessible bookmarks you can find api at this link

http://www.delicious.com/help/feeds.

and for accessing private bookmarks you can find api at this link

http://www.delicious.com/help/oauthapi

Here is the java code for fetching delicious search result based on a tag.


suppose we want to search tag/keyword "india". So.

String keyword="india" ;

 urlpath is the url which we will hit for getting result.
                                          
String urlpath="http://feeds.delicious.com/v2/json/tag/"+keyword+"?count=50";

by this url we will get recent result related to the keyword in json format.
If you want to fetch the popular result related the keyword, use the following url.

String urlpath="http://feeds.delicious.com/v2/json/popular/"+keyword+"?count=50";


for hitting the url we will use HttpClient class.


HttpClient client = new HttpClient();
GetMethod method = new GetMethod(urlpath);
   
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK){
         System.out.println("delicious service status: " + method.getStatusLine());
}

for using HttpClient, class and  GetMethod  class just import
org.apache.commons.httpclient.HttpClient;
org.apache.commons.httpclient.HttpStatus;
org.apache.commons.httpclient.methods.GetMethod;

byte[] responseBody = method.getResponseBody();

we get the response as a byte array. we can convert it to json array as following .

JSONArray  jsonArr = new JSONArray(new String(responseBody) );

now you have the output as a json array(jsonArr). you can simply traverse this array and display the output according to yourself. Here is the code snippet for traversing this array.

JSONArray tagJsonArr = null;
JSONObject jsonObj = null;

for(int i=0;i<jsonArr.length();i++)
{

             jsonObj = jsonArr.getJSONObject(i);
               System.out.println("url="+jsonObj.optString("u"));
               System.out.println("description="+jsonObj.optString("d"));
               System.out.println("date-time="+jsonObj.optString("dt"));
               

                tagJsonArr=jsonObj.getJSONArray("t");
                for(int k=0;k<tagJsonArr.length();k++)
                {
                   System.out.println("tag="+tagJsonArr.getString(k));
                                   
                }
               System.out.println(jsonObj.optString("n"));
                System.out.println(jsonObj.optString("a"));
               System.out.println("***********************************");  
               
               
            }
        }