Google Picasa API初体验

[size=x-large]
Google Picasa是一个在线的相册系统,他提供了很多API,我们可以对相册进行操作,下面就是一个简单的获得一个用户所有相册,并把相册里面所有的图片显示出来,页面我也没有做什么美化,在初步研究之后,发现它的API的功能还比较强大,以后有时间了再看看其他的功能。源代码和.war文件都太大了,上传两个图片看看。。
[/size]
[img]http://asialee.iteye.com/upload/attachment/86376/95d410fc-8e69-3a79-ae68-6729079beecb.gif[/img]
[img]http://asialee.iteye.com/upload/attachment/86378/b3e2aded-326f-3259-bcad-774b9ceaa341.gif[/img]

[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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值