📄 facebookrestclient.java
字号:
/* +---------------------------------------------------------------------------+ | Facebook Development Platform Java Client | +---------------------------------------------------------------------------+ | Copyright (c) 2007 Facebook, Inc. | | All rights reserved. | | | | Redistribution and use in source and binary forms, with or without | | modification, are permitted provided that the following conditions | | are met: | | | | 1. Redistributions of source code must retain the above copyright | | notice, this list of conditions and the following disclaimer. | | 2. Redistributions in binary form must reproduce the above copyright | | notice, this list of conditions and the following disclaimer in the | | documentation and/or other materials provided with the distribution. | | | | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR | | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES | | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. | | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, | | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT | | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF | | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | +---------------------------------------------------------------------------+ | For help with this library, contact developers-help@facebook.com | +---------------------------------------------------------------------------+*/package com.facebook.api;import java.io.BufferedInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.ProtocolException;import java.net.URL;import java.net.URLConnection;import java.net.URLEncoder;import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;import java.util.EnumSet;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;import org.json.simple.JSONArray;import org.json.simple.JSONObject;/** * Base class for interacting with the Facebook Application Programming Interface (API). * Most Facebook API methods map directly to function calls of this class. * <br/> * Instances of FacebookRestClient should be initialized via calls to * {@link #auth_createToken}, followed by {@link #auth_getSession}. * <br/> * For continually updated documentation, please refer to the * <a href="http://wiki.developers.facebook.com/index.php/API"> * Developer Wiki</a>. */public abstract class FacebookRestClient<T> implements IFacebookRestClient<T> { public static URL SERVER_URL = null; public static URL HTTPS_SERVER_URL = null; static { try { SERVER_URL = new URL(SERVER_ADDR); HTTPS_SERVER_URL = new URL(HTTPS_SERVER_ADDR); } catch (MalformedURLException e) { System.err.println("MalformedURLException: " + e.getMessage()); System.exit(1); } } protected final String _secret; protected final String _apiKey; protected final URL _serverUrl; protected String _sessionKey; protected boolean _isDesktop = false; protected int _userId = -1; /** * filled in when session is established * only used for desktop apps */ protected String _sessionSecret; /** * The number of parameters required for every request. * @see #callMethod(IFacebookMethod,Collection) */ public static int NUM_AUTOAPPENDED_PARAMS = 6; private static boolean DEBUG = false; protected Boolean _debug = null; protected File _uploadFile = null; protected static final String CRLF = "\r\n"; protected static final String PREF = "--"; protected static final int UPLOAD_BUFFER_SIZE = 512; public static final String MARKETPLACE_STATUS_DEFAULT = "DEFAULT"; public static final String MARKETPLACE_STATUS_NOT_SUCCESS = "NOT_SUCCESS"; public static final String MARKETPLACE_STATUS_SUCCESS = "SUCCESS"; protected FacebookRestClient(URL serverUrl, String apiKey, String secret, String sessionKey) { _sessionKey = sessionKey; _apiKey = apiKey; _secret = secret; _serverUrl = (null != serverUrl) ? serverUrl : SERVER_URL; } /** * The response format in which results to FacebookMethod calls are returned * @return the format: either XML, JSON, or null (API default) */ public String getResponseFormat() { return null; } /** * Retrieves whether two users are friends. * @param userId1 * @param userId2 * @return T * @see <a href="http://wiki.developers.facebook.com/index.php/Friends.areFriends"> * Developers Wiki: Friends.areFriends</a> */ public T friends_areFriends(int userId1, int userId2) throws FacebookException, IOException { return this.callMethod(FacebookMethod.FRIENDS_ARE_FRIENDS, new Pair<String, CharSequence>("uids1", Integer.toString(userId1)), new Pair<String, CharSequence>("uids2", Integer.toString(userId2))); } /** * Retrieves whether pairs of users are friends. * Returns whether the first user in <code>userIds1</code> is friends with the first user in * <code>userIds2</code>, the second user in <code>userIds1</code> is friends with the second user in * <code>userIds2</code>, etc. * @param userIds1 * @param userIds2 * @return T * @throws IllegalArgumentException if one of the collections is null, or empty, or if the * collection sizes differ. * @see <a href="http://wiki.developers.facebook.com/index.php/Friends.areFriends"> * Developers Wiki: Friends.areFriends</a> */ public T friends_areFriends(Collection<Integer> userIds1, Collection<Integer> userIds2) throws FacebookException, IOException { if (userIds1 == null || userIds2 == null || userIds1.isEmpty() || userIds2.isEmpty()) { throw new IllegalArgumentException("Collections passed to friends_areFriends should not be null or empty"); } if (userIds1.size() != userIds2.size()) { throw new IllegalArgumentException(String.format("Collections should be same size: got userIds1: %d elts; userIds2: %d elts", userIds1.size(), userIds2.size())); } return this.callMethod(FacebookMethod.FRIENDS_ARE_FRIENDS, new Pair<String, CharSequence>("uids1", delimit(userIds1)), new Pair<String, CharSequence>("uids2", delimit(userIds2))); } /** * Gets the FBML for a user's profile, including the content for both the profile box * and the profile actions. * @param userId - the user whose profile FBML to set * @return a T containing FBML markup */ public T profile_getFBML(Integer userId) throws FacebookException, IOException { return this.callMethod(FacebookMethod.PROFILE_GET_FBML, new Pair<String, CharSequence>("uid", Integer.toString(userId))); } /** * Recaches the referenced url. * @param url string representing the URL to refresh * @return boolean indicating whether the refresh succeeded */ public boolean fbml_refreshRefUrl(String url) throws FacebookException, IOException { return fbml_refreshRefUrl(new URL(url)); } /** * Helper function: assembles the parameters used by feed_publishActionOfUser and * feed_publishStoryToUser * @param feedMethod feed_publishStoryToUser / feed_publishActionOfUser * @param title title of the story * @param body body of the story * @param images optional images to be included in he story * @param priority * @return whether the call to <code>feedMethod</code> was successful */ protected boolean feedHandler(IFacebookMethod feedMethod, CharSequence title, CharSequence body, Collection<IFeedImage> images, Integer priority) throws FacebookException, IOException { ArrayList<Pair<String, CharSequence>> params = new ArrayList<Pair<String, CharSequence>>(feedMethod.numParams()); params.add(new Pair<String, CharSequence>("title", title)); if (null != body) params.add(new Pair<String, CharSequence>("body", body)); if (null != priority) params.add(new Pair<String, CharSequence>("priority", priority.toString())); handleFeedImages(params, images); return extractBoolean(this.callMethod(feedMethod, params)); } /** * Adds image parameters to a list of parameters * @param params * @param images */ protected void handleFeedImages(List<Pair<String, CharSequence>> params, Collection<IFeedImage> images) { if (images != null && images.size() > 4) { throw new IllegalArgumentException("At most four images are allowed, got " + Integer.toString(images.size())); } if (null != images && !images.isEmpty()) { int image_count = 0; for (IFeedImage image : images) { ++image_count; String imageUrl = image.getImageUrlString(); assert null != imageUrl && "".equals(imageUrl) : "Image URL must be provided"; params.add(new Pair<String, CharSequence>(String.format("image_%d", image_count), image.getImageUrlString())); assert null != image.getLinkUrl() : "Image link URL must be provided"; params.add(new Pair<String, CharSequence>(String.format("image_%d_link", image_count), image.getLinkUrl().toString())); } } } /** * Publish the notification of an action taken by a user to newsfeed. * @param title the title of the feed story (up to 60 characters, excluding tags) * @param body (optional) the body of the feed story (up to 200 characters, excluding tags) * @param images (optional) up to four pairs of image URLs and (possibly null) link URLs * @return whether the story was successfully published; false in case of permission error * @see <a href="http://wiki.developers.facebook.com/index.php/Feed.publishActionOfUser"> * Developers Wiki: Feed.publishActionOfUser</a> */ public boolean feed_publishActionOfUser(CharSequence title, CharSequence body, Collection<IFeedImage> images) throws FacebookException, IOException { return feedHandler(FacebookMethod.FEED_PUBLISH_ACTION_OF_USER, title, body, images, null); } /** * Publish the notification of an action taken by a user to newsfeed. * @param title the title of the feed story (up to 60 characters, excluding tags) * @param body (optional) the body of the feed story (up to 200 characters, excluding tags) * @return whether the story was successfully published; false in case of permission error * @see <a href="http://wiki.developers.facebook.com/index.php/Feed.publishActionOfUser"> * Developers Wiki: Feed.publishActionOfUser</a> */ public boolean feed_publishActionOfUser(CharSequence title, CharSequence body) throws FacebookException, IOException { return feed_publishActionOfUser(title, body, null); } /** * Call this function to retrieve the session information after your user has * logged in. * @param authToken the token returned by auth_createToken or passed back to your callback_url. */ public abstract String auth_getSession(String authToken) throws FacebookException, IOException; /** * Publish a story to the logged-in user's newsfeed. * @param title the title of the feed story * @param body the body of the feed story * @return whether the story was successfully published; false in case of permission error * @see <a href="http://wiki.developers.facebook.com/index.php/Feed.publishStoryToUser"> * Developers Wiki: Feed.publishStoryToUser</a> */ public boolean feed_publishStoryToUser(CharSequence title, CharSequence body) throws FacebookException, IOException { return feed_publishStoryToUser(title, body, null, null); }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -