📄 doubanservice.java
字号:
package com.google.gdata.client.douban;import java.io.IOException;import java.net.MalformedURLException;import java.net.URL;import java.util.ArrayList;import java.util.Collection;import java.util.List;import java.util.Map;import net.oauth.OAuth;import net.oauth.OAuthAccessor;import net.oauth.OAuthConsumer;import net.oauth.OAuthMessage;import net.oauth.OAuthServiceProvider;import net.oauth.client.OAuthClient;import net.oauth.client.httpclient4.HttpClient4;import com.google.gdata.client.Query;import com.google.gdata.client.Service;import com.google.gdata.client.Query.CustomParameter;import com.google.gdata.client.http.GoogleGDataRequest;import com.google.gdata.data.BaseEntry;import com.google.gdata.data.ExtensionProfile;import com.google.gdata.data.TextConstruct;import com.google.gdata.data.douban.Attribute;import com.google.gdata.data.douban.CollectionEntry;import com.google.gdata.data.douban.CollectionFeed;import com.google.gdata.data.douban.MiniblogEntry;import com.google.gdata.data.douban.MiniblogFeed;import com.google.gdata.data.douban.Namespaces;import com.google.gdata.data.douban.NoteEntry;import com.google.gdata.data.douban.NoteFeed;import com.google.gdata.data.douban.ReviewEntry;import com.google.gdata.data.douban.ReviewFeed;import com.google.gdata.data.douban.Status;import com.google.gdata.data.douban.Subject;import com.google.gdata.data.douban.SubjectEntry;import com.google.gdata.data.douban.SubjectFeed;import com.google.gdata.data.douban.Tag;import com.google.gdata.data.douban.TagEntry;import com.google.gdata.data.douban.TagFeed;import com.google.gdata.data.douban.UserEntry;import com.google.gdata.data.douban.UserFeed;import com.google.gdata.data.extensions.Rating;import com.google.gdata.util.ContentType;import com.google.gdata.util.ServiceException;public class DoubanService extends Service { protected String apiKey; protected String apiParam; protected String secret; protected boolean private_read;// public static OAuthClient CLIENT = new OAuthHttpClient(// new HttpClientPool() {// // This trivial 'pool' simply allocates a new client every time.// // More efficient implementations are possible.// public HttpClient getHttpClient(URL server) {// return new HttpClient();// }// }); public static OAuthClient CLIENT = new OAuthClient(new HttpClient4()); protected OAuthAccessor accessor; protected OAuthAccessor requestAccessor; protected List<Map.Entry<String, String>> parameters; protected OAuthConsumer client; static String requestTokenURL = "http://www.douban.com/service/auth/request_token"; static String userAuthorizationURL = "http://www.douban.com/service/auth/authorize"; static String accessTokenURL = "http://www.douban.com/service/auth/access_token"; /** * 构造豆瓣服务实例,仅支持只读操作 * * @param applicationName * 应用名称 * @param apiKey * douban的api key */ public DoubanService(String applicationName, String apiKey) { ExtensionProfile profile = getExtensionProfile(); this.apiKey = apiKey; this.apiParam = "apikey=" + apiKey; profile.addDeclarations(new UserEntry()); profile.addDeclarations(new SubjectEntry()); profile.addDeclarations(new ReviewEntry()); profile.addDeclarations(new CollectionEntry()); profile.addDeclarations(new TagEntry()); profile.addDeclarations(new NoteEntry()); profile.addDeclarations(new MiniblogEntry()); requestFactory = new GoogleGDataRequest.Factory(); this.accessor = null; if (applicationName != null) { requestFactory.setHeader("User-Agent", applicationName + " " + getServiceVersion()); } else { requestFactory.setHeader("User-Agent", getServiceVersion()); } this.private_read = false; } /** * 构造豆瓣服务实例,需要oauth授权,支持读写操作 * * @param applicationName * 应用名称 * @param apiKey * douban的api key * @param secret * douban的api私钥 */ public DoubanService(String applicationName, String apiKey, String secret) { this(applicationName, apiKey); this.apiKey = apiKey; this.secret = secret; OAuthServiceProvider provider = new OAuthServiceProvider( requestTokenURL, userAuthorizationURL, accessTokenURL); this.client = new OAuthConsumer(null, apiKey, secret, provider); this.accessor = new OAuthAccessor(this.client); this.requestAccessor = new OAuthAccessor(this.client); this.client.setProperty("oauth_signature_method", OAuth.HMAC_SHA1); this.private_read = false; } /** * 构造豆瓣服务实例,支持使用私钥验证的只读操作 * * @param applicationName * 应用名称 * @param apiKey * douban的api key * @param secret * douban的api私钥 * @param private_read * 是否支持私钥验证的只读操作 */ public DoubanService(String applicationName, String apiKey, String secret, boolean private_read) { this(applicationName, apiKey); this.apiKey = apiKey; this.secret = secret; OAuthServiceProvider provider = new OAuthServiceProvider( requestTokenURL, userAuthorizationURL, accessTokenURL); this.client = new OAuthConsumer(null, apiKey, secret, provider); this.accessor = new OAuthAccessor(this.client); this.requestAccessor = new OAuthAccessor(this.client); this.client.setProperty("oauth_signature_method", OAuth.HMAC_SHA1); this.private_read = private_read; } /** * 获取授权的URL * 需要授权的用户通过该URL进行授权,授权成功后跳转到callback指向的URL * * @param callback * 如果包含这个参数,认证成功后浏览器会被重定向到该URL */ public String getAuthorizationUrl(String callback) { String authorization_url = null; try { CLIENT.getRequestToken(this.requestAccessor); authorization_url = accessor.consumer.serviceProvider.userAuthorizationURL + "?" + "oauth_token=" + this.requestAccessor.requestToken; if (callback != null) authorization_url += "&oauth_callback=" + callback; } catch (Exception e) { e.printStackTrace(); } return authorization_url; } public String getRequestToken() { return this.requestAccessor.requestToken; } public void setRequestToken(String token) { this.requestAccessor.requestToken = token; } public String getRequestTokenSecret() { return this.requestAccessor.tokenSecret; } public void setRequestTokenSecret(String tokenSecret) { this.requestAccessor.tokenSecret = tokenSecret; } /** * 设置访问token * * * @param oauth_token * 用户授权后得到的访问token * @param oauth_token_secret * 用户授权后得到的访问token的秘钥 */ public ArrayList<String> setAccessToken(String oauth_token, String oauth_token_secret) { this.accessor.accessToken = oauth_token; this.accessor.tokenSecret = oauth_token_secret; ArrayList<String> tokens = new ArrayList<String>(2); tokens.add(this.accessor.accessToken); tokens.add(this.accessor.tokenSecret); return tokens; } /** * 获取访问token * */ public ArrayList<String> getAccessToken() { OAuthMessage result; try { result = CLIENT.invoke(this.requestAccessor, accessor.consumer.serviceProvider.accessTokenURL, OAuth .newList("oauth_token", this.requestAccessor.requestToken)); Map<String, String> responseParameters = OAuth.newMap(result .getParameters()); this.accessor.accessToken = responseParameters.get("oauth_token"); this.accessor.tokenSecret = responseParameters .get("oauth_token_secret"); ArrayList<String> tokens = new ArrayList<String>(2); tokens.add(this.accessor.accessToken); tokens.add(this.accessor.tokenSecret); return tokens; } catch (Exception e) { e.printStackTrace(); } return null; } private static final String toString(Object from) { return (from == null) ? null : from.toString(); } @SuppressWarnings("unchecked") public GDataRequest createFeedRequest(Query query) throws IOException, ServiceException { GDataRequest request = null; OAuthMessage oauthRequest = null; setTimeouts(request); if(this.accessor == null){ List<CustomParameter> customParams = query.getCustomParameters(); customParams.add(new CustomParameter("apikey", this.apiKey)); request =super.requestFactory.getRequest(query, super.getContentType()); return request; } request =super.requestFactory.getRequest(query, super.getContentType()); try { Collection<Map.Entry<String, String>> p = new ArrayList<Map.Entry<String, String>>(); p.add(new OAuth.Parameter("oauth_version", "1.0")); String methodType = "GET"; GDataRequest.RequestType type= GDataRequest.RequestType.QUERY; switch (type) { case INSERT: methodType = "POST"; break; case UPDATE: methodType = "PUT"; break; case DELETE: methodType = "DELETE"; break; } if(this.private_read == true) { oauthRequest = this.requestAccessor.newRequestMessage(methodType, query.getUrl().toString(), p); } else { oauthRequest = this.accessor.newRequestMessage(methodType, query.getUrl().toString(), p); } } catch (Exception e) { e.printStackTrace(); } parameters = oauthRequest.getParameters(); String url = "OAuth realm=\"\""; for (Map.Entry parameter : parameters) { url += ", "; url += OAuth.percentEncode(toString(parameter.getKey())); url += "=\""; url += OAuth.percentEncode(toString(parameter.getValue())); url += "\""; } request.setHeader("Authorization", url); return request; } @SuppressWarnings("unchecked") @Override public GDataRequest createRequest(GDataRequest.RequestType type, URL requestUrl, ContentType contentType) throws IOException, ServiceException { GDataRequest request = null; OAuthMessage oauthRequest = null; if(this.accessor == null){ String url = requestUrl.toString(); if(url.indexOf('?')==-1){ url = url + "?" + this.apiParam; } else { url = url + "&" + this.apiParam; } request = super.createRequest(type, new URL(url), contentType); return request; } request = super.createRequest(type, requestUrl, contentType); try { Collection<Map.Entry<String, String>> p = new ArrayList<Map.Entry<String, String>>(); p.add(new OAuth.Parameter("oauth_version", "1.0")); String methodType = "GET"; switch (type) { case INSERT: methodType = "POST"; break; case UPDATE: methodType = "PUT"; break; case DELETE: methodType = "DELETE"; break; } if(this.private_read == true) { oauthRequest = this.requestAccessor.newRequestMessage(methodType, requestUrl.toString(), p); } else { oauthRequest = this.accessor.newRequestMessage(methodType, requestUrl.toString(), p); } } catch (Exception e) { e.printStackTrace(); } parameters = oauthRequest.getParameters(); String url = "OAuth realm=\"\""; for (Map.Entry parameter : parameters) { url += ", "; url += OAuth.percentEncode(toString(parameter.getKey())); url += "=\""; url += OAuth.percentEncode(toString(parameter.getValue())); url += "\""; } request.setHeader("Authorization", url); return request; } public <E extends BaseEntry<?>> E getEntry(String entryUrl, Class<E> entryClass) throws IOException, ServiceException { return super.getEntry(new URL(entryUrl), entryClass); } /** * 得到用户信息 * * @param userId * 用户的id字符串 */ public UserEntry getUser(String userId) throws IOException, ServiceException { String url = Namespaces.userURL + "/" + userId; return getEntry(url, UserEntry.class); } public UserEntry getAuthorizedUser() throws IOException, ServiceException { String url = Namespaces.userURL + "/%40me"; return getEntry(url, UserEntry.class); } /** * 查找用户信息 *
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -