Google Picasa API初體驗

Google Picasa是一個在線的相冊系統,他提供了很多API,我們可以對相冊進行操作,下面就是一個簡單的獲得一個用戶所有相冊,並把相冊裏面所有的圖片顯示出來,頁面我也沒有做什麼美化,在初步研究之後,發現它的API的功能還比較強大,以後有時間了再看看其他的功能。源代碼和.war文件都太大了,上傳兩個圖片看看。。




[size=medium]
Java代碼  收藏代碼
  1. import java.io.BufferedInputStream;  
  2. import java.io.File;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.OutputStream;  
  6. import java.net.MalformedURLException;  
  7. import java.net.URL;  
  8. import java.util.ArrayList;  
  9. import java.util.Hashtable;  
  10. import java.util.List;  
  11. import java.util.Map;  
  12.   
  13. import javax.servlet.ServletException;  
  14. import javax.servlet.http.HttpServlet;  
  15. import javax.servlet.http.HttpServletRequest;  
  16. import javax.servlet.http.HttpServletResponse;  
  17.   
  18. import com.google.gdata.client.photos.PicasawebService;  
  19. import com.google.gdata.data.Link;  
  20. import com.google.gdata.data.photos.AlbumEntry;  
  21. import com.google.gdata.data.photos.AlbumFeed;  
  22. import com.google.gdata.data.photos.GphotoEntry;  
  23. import com.google.gdata.data.photos.PhotoEntry;  
  24. import com.google.gdata.data.photos.UserFeed;  
  25. import com.google.gdata.util.AuthenticationException;  
  26. import com.google.gdata.util.ServiceException;  
  27.   
  28. public class PicasaServlet extends HttpServlet {  
  29.   
  30.     /** 
  31.      * This is a serial version generated by eclipse. 
  32.      */  
  33.     private static final long serialVersionUID = -6737329335179440491L;  
  34.   
  35.     /** 
  36.      * This is the api prefix of the goold picasa forum. 
  37.      */  
  38.     private static final String API_PREFIX = "http://picasaweb.google.com/data/feed/api/user/";  
  39.   
  40.     /** 
  41.      * This method is to deal with the HTTP GET request. 
  42.      *  
  43.      * @param request 
  44.      *            The HttPServletRequest object. 
  45.      * @param response 
  46.      *            The HttpServletResponse object. 
  47.      * @throws ServletException 
  48.      *             Throws servlet exception if encounters some server errors. 
  49.      * @throws IOException 
  50.      *             Throws IOException if encounter some io write/read errors. 
  51.      */  
  52.     @Override  
  53.     protected void doGet(HttpServletRequest request,  
  54.             HttpServletResponse response) throws ServletException, IOException {  
  55.         doPost(request, response);  
  56.     }  
  57.   
  58.     /** 
  59.      * This method is to deal with the HTTP Post request. Download the image and 
  60.      * corresponding thumbnails image with emailAddress and password 
  61.      * authentication, and save it to "/image" folder, this can be displayed 
  62.      * directly in the client. 
  63.      *  
  64.      * @param request 
  65.      *            The HttPServletRequest object. 
  66.      * @param response 
  67.      *            The HttpServletResponse object. 
  68.      * @throws ServletException 
  69.      *             Throws servlet exception if encounters some server errors. 
  70.      * @throws IOException 
  71.      *             Throws IOException if encounter some io write/read errors. 
  72.      */  
  73.     @SuppressWarnings("deprecation")  
  74.     @Override  
  75.     protected void doPost(HttpServletRequest request,  
  76.             HttpServletResponse response) throws ServletException, IOException {  
  77.         String emailAddress = request.getParameter("emailAddress");  
  78.         String password = request.getParameter("password");  
  79.         String realPath = request.getRealPath("/image");  
  80.         Map<String, List<String>> albumPhotos = generatePhoto(emailAddress,  
  81.                 password, realPath);  
  82.         request.setAttribute("albumPhotos", albumPhotos);  
  83.         request.getRequestDispatcher("/result.jsp").forward(request, response);  
  84.     }  
  85.       
  86.     /** 
  87.      * This method is to get the album, and all the photo's name and thumbnail 
  88.      * format name, and the photo's description. 
  89.      *  
  90.      * @param emailAddress 
  91.      *            The email address which you used to authenticated. 
  92.      * @param password 
  93.      *            The password which you used to authenticated. 
  94.      * @param realPath 
  95.      *            The realPath you want to save the images. 
  96.      * @return Map<String,List<Sring>> which represents the album and all the 
  97.      *         photos in that album. It always have the following format. 
  98.      *         albumName: test.png i_test.png This is the image's description. 
  99.      * @throws IOException 
  100.      *             Throws IOException if encounter some io write/read errors. 
  101.      */  
  102.     public Map<String, List<String>> generatePhoto(String emailAddress,  
  103.             String password, String realPath) throws IOException {  
  104.         if (emailAddress != null && password != null) {  
  105.             try {  
  106.                 PicasawebService picasaService = buildPicasaWebService(  
  107.                         "Picasa", emailAddress, password);  
  108.                 List<AlbumEntry> albums = getAlbums(picasaService, emailAddress);  
  109.                 Map<String, List<String>> albumPhotos = new Hashtable<String, List<String>>();  
  110.                 for (AlbumEntry albumEntry : albums) {  
  111.                     List<PhotoEntry> photoEntrys = getPhotos(picasaService,  
  112.                             albumEntry);  
  113.                     if (photoEntrys.size() > 0) {  
  114.                         List<String> photos = new ArrayList<String>();  
  115.                         for (PhotoEntry photoEntry : photoEntrys) {  
  116.                             String thumbnailsName = writeImage(photoEntry  
  117.                                     .getMediaThumbnails().get(0).getUrl(),  
  118.                                     realPath, false);  
  119.                             String originalName = writeImage(photoEntry  
  120.                                     .getMediaContents().get(0).getUrl(),  
  121.                                     realPath, true);  
  122.                             photos.add(thumbnailsName);  
  123.                             photos.add(originalName);  
  124.                             photos.add(photoEntry.getDescription()  
  125.                                     .getPlainText());  
  126.                         }  
  127.                         albumPhotos.put(albumEntry.getName(), photos);  
  128.                     }  
  129.                 }  
  130.                 return albumPhotos;  
  131.             } catch (AuthenticationException e) {  
  132.                 e.printStackTrace();  
  133.             } catch (ServiceException e) {  
  134.                 e.printStackTrace();  
  135.             }  
  136.         }  
  137.         return new Hashtable<String, List<String>>();  
  138.     }  
  139.   
  140.     /** 
  141.      * This is method is to build a PicasawebService object using the 
  142.      * emailAddress and password, and the appName. 
  143.      *  
  144.      * @param appName 
  145.      *            The appname you want to set, in this program we set it 
  146.      *            "picasa" 
  147.      * @param emailAddress 
  148.      *            The email address of you used to authenticated. 
  149.      * @param password 
  150.      *            The password you used to authenticated. 
  151.      * @return The PicasawebService object. 
  152.      * @throws AuthenticationException 
  153.      *             If there exist some authentication exception occur. 
  154.      */  
  155.     public PicasawebService buildPicasaWebService(String appName,  
  156.             String emailAddress, String password)  
  157.             throws AuthenticationException {  
  158.         PicasawebService picasaService = new PicasawebService(appName);  
  159.         picasaService.setUserCredentials(emailAddress, password);  
  160.         return picasaService;  
  161.     }  
  162.   
  163.   
  164.     /** 
  165.      * This method is to extract a user's album. 
  166.      *  
  167.      * @param picasaService 
  168.      *            The picasawebService object, we use this object to get the 
  169.      *            user's feed. 
  170.      * @param username 
  171.      *            The user name which we want to get the all the album. 
  172.      * @return A list of AlbumEntrys. 
  173.      * @throws IOException 
  174.      *             There is some write/read exception occured. 
  175.      * @throws ServiceException 
  176.      *             This is some service exception occur, for example, the wrong 
  177.      *             URL 
  178.      */  
  179.     @SuppressWarnings("unchecked")  
  180.     public List<AlbumEntry> getAlbums(PicasawebService picasaService,  
  181.             String username) throws IOException, ServiceException {  
  182.   
  183.         String albumUrl = API_PREFIX + username;  
  184.         UserFeed userFeed = picasaService.getFeed(new URL(albumUrl),  
  185.                 UserFeed.class);  
  186.   
  187.         List<GphotoEntry> entries = userFeed.getEntries();  
  188.         List<AlbumEntry> albums = new ArrayList<AlbumEntry>();  
  189.         for (GphotoEntry entry : entries) {  
  190.             GphotoEntry adapted = entry.getAdaptedEntry();  
  191.             if (adapted instanceof AlbumEntry) {  
  192.                 albums.add((AlbumEntry) adapted);  
  193.             }  
  194.         }  
  195.         return albums;  
  196.     }  
  197.   
  198.     /** 
  199.      * This method is to extract all the photos from a particular album. 
  200.      *  
  201.      * @param picasaService 
  202.      *            The picasawebService object, we use this object to get the 
  203.      *            user's feed. 
  204.      * @param album 
  205.      *            The AlbumEntry object which you want to get all the photos 
  206.      *            from it. 
  207.      * @return A list of PhotoEntry object. 
  208.      * @throws IOException 
  209.      *             There is some write/read exception occured. 
  210.      * @throws ServiceException 
  211.      *             This is some service exception occur, for example, the wrong 
  212.      *             URL 
  213.      */  
  214.     @SuppressWarnings("unchecked")  
  215.     public List<PhotoEntry> getPhotos(PicasawebService picasaService,  
  216.             AlbumEntry album) throws IOException, ServiceException {  
  217.   
  218.         String feedHref = getLinkByRel(album.getLinks(), Link.Rel.FEED);  
  219.         AlbumFeed albumFeed = picasaService.getFeed(new URL(feedHref),  
  220.                 AlbumFeed.class);  
  221.   
  222.         List<GphotoEntry> entries = albumFeed.getEntries();  
  223.         List<PhotoEntry> photos = new ArrayList<PhotoEntry>();  
  224.         for (GphotoEntry entry : entries) {  
  225.             GphotoEntry adapted = entry.getAdaptedEntry();  
  226.             if (adapted instanceof PhotoEntry) {  
  227.                 photos.add((PhotoEntry) adapted);  
  228.             }  
  229.         }  
  230.         return photos;  
  231.     }  
  232.       
  233.   
  234.     /** 
  235.      * This method is a helper method, is to get the href from with a link's 
  236.      * name from the corresponding links collection. 
  237.      *  
  238.      * @param links 
  239.      *            The Link collection you want to elect from. 
  240.      * @param relValue 
  241.      *            The corresponding value. 
  242.      * @return The real link's href value. 
  243.      */  
  244.     public String getLinkByRel(List<Link> links, String relValue) {  
  245.         for (Link link : links) {  
  246.             if (relValue.equals(link.getRel())) {  
  247.                 return link.getHref();  
  248.             }  
  249.         }  
  250.         throw new IllegalArgumentException("Missing " + relValue + " link.");  
  251.     }  
  252.       
  253.   
  254.     /** 
  255.      * This method is to write the urlAddress's image to the server's "/image" 
  256.      * folder, and if it is the thumbnail, we just directly add a "i_" prefix to 
  257.      * distinguish, 
  258.      *  
  259.      * @param urlAddress 
  260.      *            The image URL address, it is a String object. 
  261.      * @param realPath 
  262.      *            The real path of "/image" folder, in that path you want to 
  263.      *            save this image. 
  264.      * @param isThumbnail 
  265.      *            Whether the image is thumbnail. 
  266.      * @return The filename of the image, if it is thumbnail manner. 
  267.      */  
  268.     public String writeImage(String urlAddress, String realPath,  
  269.             boolean isThumbnail) {  
  270.         try {  
  271.             URL url = new URL(urlAddress);  
  272.             BufferedInputStream bis = new BufferedInputStream(url.openStream());  
  273.             String fileName = getFileName(urlAddress, isThumbnail);  
  274.             byte[] bytes = new byte[1024];  
  275.             OutputStream bos = new FileOutputStream(new File(realPath + "\\"  
  276.                     + fileName));  
  277.             int len;  
  278.             while ((len = bis.read(bytes)) > 0) {  
  279.                 bos.write(bytes, 0, len);  
  280.             }  
  281.             bis.close();  
  282.             bos.flush();  
  283.             bos.close();  
  284.             return fileName;  
  285.         } catch (MalformedURLException e) {  
  286.             e.printStackTrace();  
  287.         } catch (IOException e) {  
  288.             e.printStackTrace();  
  289.         }  
  290.         return "";  
  291.     }  
  292.   
  293.     /** 
  294.      * This method is to get the file name from the URL address, and if it is 
  295.      * thumbnail, add a "i_" prefix to distinguish. 
  296.      *  
  297.      * @param urlAddress 
  298.      *            The URL address that contains the real image address. 
  299.      * @param isThumbnail 
  300.      *            Whether this image is thumbnail 
  301.      * @return The formated filename of this image represented by the URL 
  302.      *         address. 
  303.      */  
  304.     public String getFileName(String urlAddress, boolean isThumbnail) {  
  305.         int lastURLSeparater = urlAddress.lastIndexOf("/");  
  306.         if (isThumbnail) {  
  307.             return urlAddress.substring(lastURLSeparater + 1);  
  308.         } else {  
  309.             return "i_" + urlAddress.substring(lastURLSeparater + 1);  
  310.         }  
  311.     }  
  312. }  
[/size]
[size=medium]
Html代碼  收藏代碼
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   
  4.     "http://www.w3.org/TR/html4/loose.dtd">  
  5. <html>  
  6. <head>  
  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  8. <title>Input the emailAddress and password</title>  
  9. </head>  
  10. <body>  
  11. <form action="servlet/picasaServlet" method="post">  
  12.     <label>Input emailAddress:</label>  
  13.     <input type="text" name="emailAddress" />  
  14.     <label>Input password:</label>  
  15.     <input type="password"" name="password" />  
  16.     <input type="submit" value="submit">  
  17. </form>  
  18. </body>  
  19. </html>  

[/size]
[size=medium]
Html代碼  收藏代碼
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@ page import="java.util.*" %>  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   
  5.     "http://www.w3.org/TR/html4/loose.dtd">  
  6. <html>  
  7. <head>  
  8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  9. <title>Input the emailAddress and password</title>  
  10. </head>  
  11. <body>  
  12.       
  13.     <%  
  14.         Map<String,List<String>> albumPhotos =   
  15.             (Map<String,List<String>>)request.getAttribute("albumPhotos");  
  16.         for(Iterator<String> it = albumPhotos.keySet().iterator(); it.hasNext();){  
  17.             String albumName = it.next();  
  18.             List<String> photos = albumPhotos.get(albumName);  
  19.     %>  
  20.         albumName:<%=albumName%><br>  
  21.         <%for(int i = 0; i < photos.size(); i+=3){%>  
  22.         Thumbnails: <img alt="" src="<%=request.getContextPath()%>/image/<%=photos.get(i)%>"><br>  
  23.         Original: <img alt="" src="<%=request.getContextPath()%>/image/<%=photos.get(i+1)%>"><br>  
  24.         Description: <%=photos.get(i+2)%>  
  25.           
  26.     <%  
  27.             }  
  28.         }  
  29.     %>  
  30.       
  31. </body>  
  32. </html>  

[/size]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章