`

Google Picasa API初体验

    博客分类:
  • java
阅读更多

Google Picasa是一个在线的相册系统,他提供了很多API,我们可以对相册进行操作,下面就是一个简单的获得一个用户所有相册,并把相册里面所有的图片显示出来,页面我也没有做什么美化,在初步研究之后,发现它的API的功能还比较强大,以后有时间了再看看其他的功能。源代码和.war文件都太大了,上传两个图片看看。。




[size=medium]
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.Link;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.data.photos.AlbumFeed;
import com.google.gdata.data.photos.GphotoEntry;
import com.google.gdata.data.photos.PhotoEntry;
import com.google.gdata.data.photos.UserFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

public class PicasaServlet extends HttpServlet {

	/**
	 * This is a serial version generated by eclipse.
	 */
	private static final long serialVersionUID = -6737329335179440491L;

	/**
	 * This is the api prefix of the goold picasa forum.
	 */
	private static final String API_PREFIX = "http://picasaweb.google.com/data/feed/api/user/";

	/**
	 * This method is to deal with the HTTP GET request.
	 * 
	 * @param request
	 *            The HttPServletRequest object.
	 * @param response
	 *            The HttpServletResponse object.
	 * @throws ServletException
	 *             Throws servlet exception if encounters some server errors.
	 * @throws IOException
	 *             Throws IOException if encounter some io write/read errors.
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * This method is to deal with the HTTP Post request. Download the image and
	 * corresponding thumbnails image with emailAddress and password
	 * authentication, and save it to "/image" folder, this can be displayed
	 * directly in the client.
	 * 
	 * @param request
	 *            The HttPServletRequest object.
	 * @param response
	 *            The HttpServletResponse object.
	 * @throws ServletException
	 *             Throws servlet exception if encounters some server errors.
	 * @throws IOException
	 *             Throws IOException if encounter some io write/read errors.
	 */
	@SuppressWarnings("deprecation")
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String emailAddress = request.getParameter("emailAddress");
		String password = request.getParameter("password");
		String realPath = request.getRealPath("/image");
		Map<String, List<String>> albumPhotos = generatePhoto(emailAddress,
				password, realPath);
		request.setAttribute("albumPhotos", albumPhotos);
		request.getRequestDispatcher("/result.jsp").forward(request, response);
	}
	
	/**
	 * This method is to get the album, and all the photo's name and thumbnail
	 * format name, and the photo's description.
	 * 
	 * @param emailAddress
	 *            The email address which you used to authenticated.
	 * @param password
	 *            The password which you used to authenticated.
	 * @param realPath
	 *            The realPath you want to save the images.
	 * @return Map<String,List<Sring>> which represents the album and all the
	 *         photos in that album. It always have the following format.
	 *         albumName: test.png i_test.png This is the image's description.
	 * @throws IOException
	 *             Throws IOException if encounter some io write/read errors.
	 */
	public Map<String, List<String>> generatePhoto(String emailAddress,
			String password, String realPath) throws IOException {
		if (emailAddress != null && password != null) {
			try {
				PicasawebService picasaService = buildPicasaWebService(
						"Picasa", emailAddress, password);
				List<AlbumEntry> albums = getAlbums(picasaService, emailAddress);
				Map<String, List<String>> albumPhotos = new Hashtable<String, List<String>>();
				for (AlbumEntry albumEntry : albums) {
					List<PhotoEntry> photoEntrys = getPhotos(picasaService,
							albumEntry);
					if (photoEntrys.size() > 0) {
						List<String> photos = new ArrayList<String>();
						for (PhotoEntry photoEntry : photoEntrys) {
							String thumbnailsName = writeImage(photoEntry
									.getMediaThumbnails().get(0).getUrl(),
									realPath, false);
							String originalName = writeImage(photoEntry
									.getMediaContents().get(0).getUrl(),
									realPath, true);
							photos.add(thumbnailsName);
							photos.add(originalName);
							photos.add(photoEntry.getDescription()
									.getPlainText());
						}
						albumPhotos.put(albumEntry.getName(), photos);
					}
				}
				return albumPhotos;
			} catch (AuthenticationException e) {
				e.printStackTrace();
			} catch (ServiceException e) {
				e.printStackTrace();
			}
		}
		return new Hashtable<String, List<String>>();
	}

	/**
	 * This is method is to build a PicasawebService object using the
	 * emailAddress and password, and the appName.
	 * 
	 * @param appName
	 *            The appname you want to set, in this program we set it
	 *            "picasa"
	 * @param emailAddress
	 *            The email address of you used to authenticated.
	 * @param password
	 *            The password you used to authenticated.
	 * @return The PicasawebService object.
	 * @throws AuthenticationException
	 *             If there exist some authentication exception occur.
	 */
	public PicasawebService buildPicasaWebService(String appName,
			String emailAddress, String password)
			throws AuthenticationException {
		PicasawebService picasaService = new PicasawebService(appName);
		picasaService.setUserCredentials(emailAddress, password);
		return picasaService;
	}


	/**
	 * This method is to extract a user's album.
	 * 
	 * @param picasaService
	 *            The picasawebService object, we use this object to get the
	 *            user's feed.
	 * @param username
	 *            The user name which we want to get the all the album.
	 * @return A list of AlbumEntrys.
	 * @throws IOException
	 *             There is some write/read exception occured.
	 * @throws ServiceException
	 *             This is some service exception occur, for example, the wrong
	 *             URL
	 */
	@SuppressWarnings("unchecked")
	public List<AlbumEntry> getAlbums(PicasawebService picasaService,
			String username) throws IOException, ServiceException {

		String albumUrl = API_PREFIX + username;
		UserFeed userFeed = picasaService.getFeed(new URL(albumUrl),
				UserFeed.class);

		List<GphotoEntry> entries = userFeed.getEntries();
		List<AlbumEntry> albums = new ArrayList<AlbumEntry>();
		for (GphotoEntry entry : entries) {
			GphotoEntry adapted = entry.getAdaptedEntry();
			if (adapted instanceof AlbumEntry) {
				albums.add((AlbumEntry) adapted);
			}
		}
		return albums;
	}

	/**
	 * This method is to extract all the photos from a particular album.
	 * 
	 * @param picasaService
	 *            The picasawebService object, we use this object to get the
	 *            user's feed.
	 * @param album
	 *            The AlbumEntry object which you want to get all the photos
	 *            from it.
	 * @return A list of PhotoEntry object.
	 * @throws IOException
	 *             There is some write/read exception occured.
	 * @throws ServiceException
	 *             This is some service exception occur, for example, the wrong
	 *             URL
	 */
	@SuppressWarnings("unchecked")
	public List<PhotoEntry> getPhotos(PicasawebService picasaService,
			AlbumEntry album) throws IOException, ServiceException {

		String feedHref = getLinkByRel(album.getLinks(), Link.Rel.FEED);
		AlbumFeed albumFeed = picasaService.getFeed(new URL(feedHref),
				AlbumFeed.class);

		List<GphotoEntry> entries = albumFeed.getEntries();
		List<PhotoEntry> photos = new ArrayList<PhotoEntry>();
		for (GphotoEntry entry : entries) {
			GphotoEntry adapted = entry.getAdaptedEntry();
			if (adapted instanceof PhotoEntry) {
				photos.add((PhotoEntry) adapted);
			}
		}
		return photos;
	}
	

	/**
	 * This method is a helper method, is to get the href from with a link's
	 * name from the corresponding links collection.
	 * 
	 * @param links
	 *            The Link collection you want to elect from.
	 * @param relValue
	 *            The corresponding value.
	 * @return The real link's href value.
	 */
	public String getLinkByRel(List<Link> links, String relValue) {
		for (Link link : links) {
			if (relValue.equals(link.getRel())) {
				return link.getHref();
			}
		}
		throw new IllegalArgumentException("Missing " + relValue + " link.");
	}
	

	/**
	 * This method is to write the urlAddress's image to the server's "/image"
	 * folder, and if it is the thumbnail, we just directly add a "i_" prefix to
	 * distinguish,
	 * 
	 * @param urlAddress
	 *            The image URL address, it is a String object.
	 * @param realPath
	 *            The real path of "/image" folder, in that path you want to
	 *            save this image.
	 * @param isThumbnail
	 *            Whether the image is thumbnail.
	 * @return The filename of the image, if it is thumbnail manner.
	 */
	public String writeImage(String urlAddress, String realPath,
			boolean isThumbnail) {
		try {
			URL url = new URL(urlAddress);
			BufferedInputStream bis = new BufferedInputStream(url.openStream());
			String fileName = getFileName(urlAddress, isThumbnail);
			byte[] bytes = new byte[1024];
			OutputStream bos = new FileOutputStream(new File(realPath + "\\"
					+ fileName));
			int len;
			while ((len = bis.read(bytes)) > 0) {
				bos.write(bytes, 0, len);
			}
			bis.close();
			bos.flush();
			bos.close();
			return fileName;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * This method is to get the file name from the URL address, and if it is
	 * thumbnail, add a "i_" prefix to distinguish.
	 * 
	 * @param urlAddress
	 *            The URL address that contains the real image address.
	 * @param isThumbnail
	 *            Whether this image is thumbnail
	 * @return The formated filename of this image represented by the URL
	 *         address.
	 */
	public String getFileName(String urlAddress, boolean isThumbnail) {
		int lastURLSeparater = urlAddress.lastIndexOf("/");
		if (isThumbnail) {
			return urlAddress.substring(lastURLSeparater + 1);
		} else {
			return "i_" + urlAddress.substring(lastURLSeparater + 1);
		}
	}
}

[/size]
[size=medium]
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Input the emailAddress and password</title>
</head>
<body>
<form action="servlet/picasaServlet" method="post">
	<label>Input emailAddress:</label>
	<input type="text" name="emailAddress" />
	<label>Input password:</label>
	<input type="password"" name="password" />
	<input type="submit" value="submit">
</form>
</body>
</html>

[/size]
[size=medium]
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Input the emailAddress and password</title>
</head>
<body>
	
	<%
		Map<String,List<String>> albumPhotos = 
			(Map<String,List<String>>)request.getAttribute("albumPhotos");
		for(Iterator<String> it = albumPhotos.keySet().iterator(); it.hasNext();){
			String albumName = it.next();
			List<String> photos = albumPhotos.get(albumName);
	%>
		albumName:<%=albumName%><br>
		<%for(int i = 0; i < photos.size(); i+=3){%>
		Thumbnails: <img alt="" src="<%=request.getContextPath()%>/image/<%=photos.get(i)%>"><br>
		Original: <img alt="" src="<%=request.getContextPath()%>/image/<%=photos.get(i+1)%>"><br>
		Description: <%=photos.get(i+2)%>
		
	<%
			}
		}
	%>
	
</body>
</html>

[/size]



  • 大小: 8.8 KB
  • 大小: 175.6 KB
0
0
分享到:
评论
3 楼 ankang2577 2010-12-11  
楼主留个能不能给我讲一下,在eclipse中如何配置picasa的API,加我QQ号771006587,谢谢了
2 楼 shjie5246 2009-05-04  
我做的时候缺少类
1 楼 shjie5246 2009-05-04  
能把相关的jar包贡献下吗,谢谢了.

相关推荐

    Google Picasa 源码

    Picasa,这款由Google推出的免费图片管理工具,自2002年发布以来,因其简洁易用的界面和强大的图片处理功能而深受用户喜爱。Picasa的核心价值在于其对图片的智能组织、浏览和编辑能力,这背后离不开精心设计的源代码...

    use pwa to access Google picasaweb

    2. **数据同步**:与Google Picasa API集成,实现本地分类与云端同步。 3. **搜索功能**:增加搜索框,支持按关键词或标签查找照片。 4. **自定义标签**:允许用户为照片添加自定义标签,方便分类和检索。 至于...

    将GoogleMap嵌入到桌面应用程序窗口

    Google Maps API是一个JavaScript库,允许开发者在网页或应用程序中嵌入交互式地图。对于桌面应用,我们需要使用WebBrowser控件来加载和显示嵌入的HTML和JavaScript内容。 1. **设置WebBrowser控件**: 在Winform...

    JAlbum 2 Picasa:转换JAlbum画廊以上传到Google Picasa网络相册-开源

    2. **设置API密钥**:为了将照片上传到Picasa,你需要一个有效的Google API密钥。访问Google Cloud Console,创建一个新的项目,并启用Picasa Web Albums Data API。然后,生成一个服务器端API密钥,并保存以备后用...

    Google Android SDK开发范例大全(PDF高清完整版1)(4-1)

    第2章 Android初体验 2.1 安装AndroidSDK与ADTplug-in 2.2 建立第一个Android项目(HelloAndroid!) 2.3 Android应用程序架构——从此开始 2.4 可视化的界面开发工具 2.5 部署应用程序到Android手机 第3章 用户人机...

    the_gif:“ gif”是一个基于picasa的网站,用于查看随机gif动画

    总结来说,"the_gif"项目是一个基于Picasa的GIF动画展示平台,它利用JavaScript实现了与Picasa API的交互,提供了一个随机浏览GIF的互动体验。这个项目不仅为用户提供了娱乐,也为开发者提供了一个学习如何使用API和...

    webp解析器

    在描述中提到的"Picasa_PhotoViewer"可能是谷歌Picasa图片查看器的一个版本,Picasa是一款流行的图片管理与查看软件。虽然Picasa已停止更新,但它在早期版本中可能就已经支持了WebP格式,让用户能够预览和管理这种...

    wordpress 图片浏览插件

    Picasa是Google的一款图片管理工具,其相册展示方式以美观和易于导航著称。这种集成可能意味着插件提供了类似于Picasa的用户体验,包括网格布局、自动播放和过渡效果等。 开发这样一个插件需要一定的编程知识,包括...

    BeDesk WebOS Open Source-开源

    Google数据API是一组用于访问Google服务的接口,如Gmail、Google日历、Picasa等。通过这些API,开发者能够将这些服务集成到自己的应用中,实现数据的同步和管理。在BeDesk的初始阶段,它模拟了Google数据API的功能,...

    Google Android SDK开发范例大全(PDF高清完整版3)(4-3)

    第2章 Android初体验 2.1 安装AndroidSDK与ADTplug-in 2.2 建立第一个Android项目(HelloAndroid!) 2.3 Android应用程序架构——从此开始 2.4 可视化的界面开发工具 2.5 部署应用程序到Android手机 第3章 用户人机...

    Google Android SDK开发范例大全(PDF完整版4)(4-4)

    第2章 Android初体验 2.1 安装AndroidSDK与ADTplug-in 2.2 建立第一个Android项目(HelloAndroid!) 2.3 Android应用程序架构——从此开始 2.4 可视化的界面开发工具 2.5 部署应用程序到Android手机 第3章 用户人机...

    Google Android SDK开发范例大全的目录

    第2章 Android初体验 2.1 安装AndroidSDK与ADTplug-in 2.2 建立第一个Android项目(HelloAndroid!) 2.3 Android应用程序架构——从此开始 2.4 可视化的界面开发工具 2.5 部署应用程序到Android手机 第3章 用户人机...

    google android sdk开发范例大全 第二版 PDF 光盘代码

    第2章 Android初体验   2.1 安装Android SDK与ADT/DDMS   2.2 创建第一个Android项目(Hello Android!)   2.3 Android应用程序架构——从此开始   2.4 可视化的界面开发工具   2.5 部署应用程序...

    android版本的介绍_2015年06月02日.pdf

    rc22a到1.0-R1,Android逐渐成熟,逐步加入了如Android Market(现Google Play)、网页浏览器、照相机支持、电子邮件传输、Gmail、Google联系人、Google日历等功能,为用户提供了一整套完善的移动操作系统体验。...

    Google Android SDK开发范例大全(完整版附部分源码).pdf

    第2章 Android初体验 2.1 安装AndroidSDK与ADTplug-in 2.2 建立第一个Android项目(HelloAndroid!) 2.3 Android应用程序架构——从此开始 2.4 可视化的界面开发工具 2.5 部署应用程序到Android手机 第3章 ...

    Android 4.0 SDK

    Android 4.0 SDK,全称为“Android Software Development Kit for Ice Cream Sandwich”,是谷歌为开发者提供的用于构建、调试和发布针对Android 4.0(API级别14)应用的工具集合。这一版本的SDK是在2011年推出,...

    Android系统介各版本比较.doc

    用户界面得到显著提升,引入了录像、蓝牙A2DP、自动蓝牙连接、上传视频到YouTube和Picasa、复制/粘贴功能等。这些新特性使得Android开始吸引开发者和用户的关注。 **Android 1.6 "Donut"** 2009年9月发布的Donut...

    Android SDK1.5新视角 (介绍AndroidSDK1.5新特性)

    在Android SDK 1.5中,Google对用户界面进行了大量的优化和改进,不仅提升了整体的美观度,还增强了用户的交互体验。核心UI组件的样式得到了微调,变得更加精致。自带应用程序如Browser、Gmail、Email、Calendar、...

Global site tag (gtag.js) - Google Analytics