Flickr example to upload photos using Java

November 8, 2009 · 10 Comments
Filed under: JAVA 

Its all for now. Stop reading any other articles on how to post a photo in flickr using Java.

I too spent a lot of time publish a image on flickr. At last I thought to post a article on this.

Step1:

Get Flickr API Keys from here http://www.flickr.com/services/api/misc.api_keys.html

Apply for a key
View your keys

Here we will get API key and Secret Key.

Step2:

Download Flickrj Library

http://flickrj.sourceforge.net/

Step3:

Execute the following program to get the Token by completing the authentication.

Authentication Type / Application deployment environment

Flickr provides different methods for authenticating your application depending on your deployment environment. For each method/environment, Flickr needs to know different information.

Web application and Callback URL
To use web authentication:

  • Direct the user to a Flickr page; the exact URL is created using the API.
  • The user will authorize your application on Flickr; or Flickr will remember an old authorization.
  • Flickr redirects the user to your callback URL; the frob is sent as a GET attribute.

The frob is necessary to complete the authentication process. So, practically speaking, your callback URL should use technology which can fetch and store the frob; e.g., JSP or PHP. More on the frob later. For more details on web authorization, consult the Flickr web authentication howto.

Desktop application
Authentication for desktop applications is similar to web authentication. However, that falls outside the scope of this Wiki page, as this is for CISC474 – Advanced Web Technologies.




Mobile application
See desktop applications.

Getting authenticated

Flickr provides some pretty good write-ups on user authentication. This Wiki page will show it in context of some real code.

WARNING: Which frob is which?

During the authentication process, your application encounters two distinct frobs:

  1. The first is generated and sent to Flickr.
  2. Flickr sends back a different one which is used to authenticate your application.

Don’t get confused — and don’t use the first frob to authenticate your application.

Java code example

This simple Java class, modelled on flickrj’s AuthExample class, shows the basic authentication process in interactive, command-line mode. This demo code is designed for web application authorization.

Make sure to download the flickrj package and include flickrj-xxx.jar in your classpath.

For a real webapp, the main should be in two servlets. The break is indicated in the code.

  1. Prompt the user to authorize the app on Flickr.com
  2. Complete the authorization

To create a Flickr object after having authenticated in the same session, then get the token from the original authentication and set the new Flickr object’s token to that (shown at the bottom of the code).

// To save space, we're using wildcard masks for the imports.  You really only need about 30 classes total for this.
import java.io.*;
import java.net.*;
import java.util.*;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import com.aetrion.flickr.*;
import com.aetrion.flickr.auth.*;
import com.aetrion.flickr.blog.*;

/**
 * Example class to illustrate the authentication process
 * based on AuthExample from flickrj.  main() runs an interactive,
 * command-line authentication process.
 */
class AuthExample
{
    static String restHost = "www.flickr.com";
    /* Every external application for Flickr needs an API key.
     * Change the apiKey and the sharedSecret to the values given to you by Flickr.
     * You can get and edit yours at http://flickr.com/services/api/keys/
     * Ideally, these are defined elsewhere, e.g. in web.xml.
     */
    static String apiKey = "yourAPIkey";		// used to ID the application
    static String sharedSecret = "yourSharedSecret"; 	// used for signed calls

    /* Of course, we need a Flickr object to work with.  Like any good poppa class, class Flickr
     * provides several methods to fetch various xxxInterface objects, saving you the trouble
     * of instantiating them manually.  That is incidental to this example, but cool nonetheless.
     */
    Flickr flickr;

    /* Flickr supports several request methods, but the flickrj package only supports REST so far.
     * So, the Flickr object needs a REST object to handle its requests.
     */
    REST rest;
    String token;	// Generated via authentication process, for tracking the session and making signed calls
    /* Flickr requires the application to send its shared secret for any signed calls.
     * This RequestContext will manage that for us, if we use it for those calls.
     * RequestContext is from the com.aetrion.flickr package.
     */
    RequestContext requestContext;	// Used for making signed calls to Flickr

    static void main(String[] args) throws ParserConfigurationException, IOException, SAXException
    {
	REST rest = new REST();
	rest.setHost(restHost);
	Flickr flickr = new Flickr(AuthExample.apiKey, rest);

	/* Flickr requires the shared secret for any signed calls. RequestContext will store and send it. */
	requestContext = RequestContext.getRequestContext();
	requestContext.setSharedSecret(AuthExample.sharedSecret);

	/* To authorize this application, generate an authentication URL and direct the user to it. */
	// First, generate a frob...
	AuthInterface authInterface = flickr.getAuthInterface();
	String firstFrob = "";
	try {
	    firstFrob = authInterface.getFrob();
	} catch(FlickrException e) {
	    e.printStackTrace();
	}
	/* ... then generate a URL with that frob, asking for a certain level of permissions ...
	 *    -- Permission.READ     (private photos)
	 *    -- Permission.WRITE    (edit info and photos; upload photos)
	 *    -- Permission.DELETE   (photos)
	 */
        URL url = authInterface.buildAuthenticationUrl(Permission.WRITE, firstFrob);
	// ... and direct the user to it.
	System.out.println("Authorize this application at the following URL:");
	System.out.println(url.toExternalForm());   // Make sure to use URL.toExternalForm()!

	// =================================================================================
	// If this were a real webapp, you would break into another servlet after this point
	// =================================================================================

	/* After the user authorizes the application, s/he will be redirected to the
	 * callback URL associated with the API key for the application; the URL
	 * will include a rehashed frob that the application can use for authentication.
	 * If this were a real web application, it would fetch the frob itself from that page.
	 * This demo merely prompts the user to fetch it for us.
	 */
	System.out.println("After you were redirected, what was the frob? (Check your URL: ...?frob=XXX)");
	BufferedReader userInput = new BufferedReader( new InputStreamReader(System.in));
	String fetchedFrob = userInput.readLine();

	/* This is the last bit of the authentication process.
	 * Take the frob that Flickr gave back to us and use it
	 * to generate an Auth(enticated widget).
	 */
        Auth auth;
	try {
	    auth = authInterface.getToken(fetchedFrob);
	    System.out.println("Authentication success");
	} catch(FlickrException e) {
	    System.out.println("Authentication failed");
	    e.printStackTrace();
	}

	/* That frob was only valid for one authentication.  The token is good for
         * making new Flickr's in a single session.
         * I don't really know how long a session lasts -- perhaps forever.
	 * To maintain the session, keep the token in memory: auth.getToken()
	 */
        System.out.println("Token: "+auth.getToken());
	System.out.println("nsid: "+auth.getUser().getId());
	/* In addition to authorizing the application, the authentication process
	 * gives us quick access to who is the logged-in user.
	 */
	System.out.println("Realname: "+auth.getUser().getRealName());
	System.out.println("Username: "+auth.getUser().getUsername());
	/* Flickr has three tiers of permissions:
	 *  -- read (private photos)
	 *  -- write (edit info and photos; upload photos)
	 *  -- delete (photos)
	 */
	System.out.println("Permission: "+auth.getPermission().getType());

	// =================================================================================
	// Use the token to create another Flickr object with this authentication
	// =================================================================================
        Flickr sameSession = new Flickr();
        sameSession.getAuth().setToken(flickr.getAuth().getToken());

}

Step4:

Publish the photo on flickr.

Use the below program to post the picture on flickr.

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.xml.sax.SAXException;

import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.RequestContext;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.contacts.ContactsInterface;
import com.aetrion.flickr.people.PeopleInterface;
import com.aetrion.flickr.photosets.PhotosetsInterface;
import com.aetrion.flickr.uploader.UploadMetaData;
import com.aetrion.flickr.uploader.Uploader;

public class flcikruploadeg1 {

	 public static void main(String[] args) throws IOException, NoSuchAlgorithmException{

	String apiKey = "YOUR API KEY";
	String token = "YOURTOKEN";
	String secretKey = "YOUR SECERET";
	String title=" Steven";
	String photo = "D:/Steven/Steven0003.jpg";
	String description="This is photo description";

	Flickr f;
	ContactsInterface c;
	PeopleInterface p;
	PhotosetsInterface o;
	Uploader up = new Uploader(apiKey,secretKey);
	REST rest;

	RequestContext requestContext;

	AuthInterface authInterface;
	String frob = "";
	//void setup() 

	   InputStream in = new FileInputStream(photo);
       ByteArrayOutputStream out = new ByteArrayOutputStream();
       int i;
       byte[] buffer = new byte[1024];
       while ((i = in.read(buffer)) != -1) {
           out.write(buffer, 0, i);
       }
       in.close();
    //   byte[] result = out.toByteArray();

	byte data[] = out.toByteArray();
	//size(500, 500);
	f= new Flickr(apiKey,secretKey,(new Flickr(apiKey)).getTransport());
	up=f.getUploader();
	authInterface=f.getAuthInterface();
	requestContext = RequestContext.getRequestContext();
	requestContext.setSharedSecret(secretKey);

	try {
	frob = authInterface.getFrob();
	System.out.println(frob);
	URL joep = authInterface.buildAuthenticationUrl(Permission.WRITE, frob);
	System.out.println(joep.toExternalForm());
	System.out.println("Press return after you granted access at this URL:");

	} catch (IOException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	} catch (SAXException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	} catch (FlickrException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	}

	try {
	Auth auth = new Auth();
	requestContext.setAuth(auth);
	//authInterface.addAuthToken();
	auth.setToken(token);
	   auth.setPermission(Permission.WRITE);
	 System.out.println("Token Is: " + auth.getToken());
	System.out.println("Permission for token: " + auth.getPermission());
	f.setAuth(auth);
	UploadMetaData uploadMetaData = new UploadMetaData(); uploadMetaData.setTitle("hello Satish");
	up.upload(data,uploadMetaData);

	} catch (IOException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	} catch (SAXException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	} catch (FlickrException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	}

	}
}

That's it check your photo on flickr,
If you have any questions please post I will help you

-Steven