📄 googleservice.java
字号:
factory.setAuthToken(new AuthSubToken(token, key)); // Flush any cookies that might contain session info for the previous user cookies.clear(); } /** * Retrieves the authentication token for the provided set of credentials. * * @param username the name of the user (an email address) * @param password the password of the user * @param captchaToken the CAPTCHA token if CAPTCHA is required (Optional) * @param captchaAnswer the respective answer of the CAPTCHA token (Optional) * @param serviceName the name of the service to which a token is required * @param applicationName the application requesting the token * @return the token * @throws AuthenticationException if authentication failed */ public String getAuthToken(String username, String password, String captchaToken, String captchaAnswer, String serviceName, String applicationName) throws AuthenticationException { Map<String, String> params = new HashMap<String, String>(); params.put("Email", username); params.put("Passwd", password); params.put("source", applicationName); params.put("service", serviceName); params.put("accountType", "HOSTED_OR_GOOGLE"); if (captchaToken != null) { params.put("logintoken", captchaToken); } if (captchaAnswer != null) { params.put("logincaptcha", captchaAnswer); } String postOutput; try { URL url = new URL(loginProtocol + "://"+ domainName + GOOGLE_LOGIN_PATH); postOutput = makePostRequest(url, params); } catch (IOException e) { AuthenticationException ae = new AuthenticationException("Error connecting with login URI"); ae.initCause(e); throw ae; } // Parse the output Map<String, String> tokenPairs = StringUtil.string2Map(postOutput.trim(), "\n", "=", true); String token = tokenPairs.get("Auth"); if (token == null) { throw getAuthException(tokenPairs); } return token; } /** * Makes a HTTP POST request to the provided {@code url} given the * provided {@code parameters}. It returns the output from the POST * handler as a String object. * * @param url the URL to post the request * @param parameters the parameters to post to the handler * @return the output from the handler * @throws IOException if an I/O exception occurs while creating/writing/reading * the request */ public static String makePostRequest(URL url, Map<String, String> parameters) throws IOException { // Open connection HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // Set properties of the connection urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Form the POST parameters StringBuilder content = new StringBuilder(); boolean first = true; for (String key : parameters.keySet()) { String value = parameters.get(key); if (!first) { content.append("&"); } content.append(URLEncoder.encode(key)).append("="); content.append(URLEncoder.encode(value)); first = false; } urlConnection.getOutputStream().write(content.toString().getBytes("utf-8")); urlConnection.getOutputStream().flush(); urlConnection.getOutputStream().close(); // Retrieve the output int responseCode = urlConnection.getResponseCode(); InputStream inputStream; if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = urlConnection.getInputStream(); } else { inputStream = urlConnection.getErrorStream(); } String string; StringBuilder outputBuilder = new StringBuilder(); if (inputStream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); while (null != (string = reader.readLine())) { outputBuilder.append(string).append('\n'); } } return outputBuilder.toString(); } /** * Returns the respective {@code AuthenticationException} given the return * values from the login URI handler. * * @param pairs the name/value pairs returned as a result of a bad authentication * @return the respective {@code AuthenticationException} for the given error */ private AuthenticationException getAuthException(Map<String, String> pairs) { String errorName = pairs.get("Error"); if ("BadAuthentication".equals(errorName)) { return new InvalidCredentialsException("Invalid credentials"); } else if ("AccountDeleted".equals(errorName)) { return new AccountDeletedException("Account deleted"); } else if ("AccountDisabled".equals(errorName)) { return new AccountDisabledException("Account disabled"); } else if ("NotVerified".equals(errorName)) { return new NotVerifiedException("Not verified"); } else if ("TermsNotAgreed".equals(errorName)) { return new TermsNotAgreedException("Terms not agreed"); } else if ("ServiceUnavailable".equals(errorName)) { return new ServiceUnavailableException("Service unavailable"); } else if ("CaptchaRequired".equals(errorName)) { String captchaPath = pairs.get("CaptchaUrl"); StringBuilder captchaUrl = new StringBuilder(); captchaUrl.append(loginProtocol).append("://").append(domainName) .append(GOOGLE_ACCOUNTS_PATH).append('/').append(captchaPath); return new CaptchaRequiredException("Captcha required", captchaUrl.toString(), pairs.get("CaptchaToken")); } else { return new AuthenticationException("Error authenticating " + "(check service name)"); } } /** * Stores the set of GoogleCookies that have been issued during previous * requests. */ protected Set<GoogleCookie> cookies = new HashSet<GoogleCookie>(); /** * Indicates whether the GoogleService should implement a local cache * for cookies returned by the GData service. If true (the default * value), then the GoogleService instance will maintain the cache and * return cookies on subsequent requests. */ protected boolean handlesCookies = true; /** * Enables or disables cookie handling. */ public void setHandlesCookies(boolean handlesCookies) { this.handlesCookies = handlesCookies; } /** * Returns {@code true} if the GoogleService is handling cookies. */ public boolean handlesCookies() { return handlesCookies; }; /** * Adds a new GoogleCookie instance to the cache. */ public void addCookie(GoogleCookie cookie) { assert handlesCookies; cookies.add(cookie); } /** * Returns the set of associated cookies returned by previous requests. */ public Set<GoogleCookie> getCookies() { // Lazy flushing of expired cookies Iterator<GoogleCookie> cookieIter = cookies.iterator(); while (cookieIter.hasNext()) { GoogleCookie cookie = cookieIter.next(); if (cookie.hasExpired()) cookieIter.remove(); } return cookies; } @Override public void setRequestFactory(GDataRequestFactory requestFactory) { if (!(requestFactory instanceof GoogleGDataRequest.Factory)) { throw new IllegalArgumentException("Invalid factory"); } this.requestFactory = requestFactory; } @Override public GDataRequest createRequest(GDataRequest.RequestType type, URL requestUrl, ContentType contentType) throws IOException, ServiceException { GoogleGDataRequest request = (GoogleGDataRequest)super.createRequest(type, requestUrl, contentType); request.setService(this); return request; } @Override public <E extends BaseEntry> E getEntry(URL entryUrl, Class<E> entryClass, DateTime ifModifiedSince) throws IOException, ServiceException { try { return super.getEntry(entryUrl, entryClass, ifModifiedSince); } catch (RedirectRequiredException e) { entryUrl = handleRedirectException(e); } catch (SessionExpiredException e) { handleSessionExpiredException(e); } return super.getEntry(entryUrl, entryClass, ifModifiedSince); } @Override public <E extends BaseEntry> E update(URL entryUrl, E entry) throws IOException, ServiceException { try { return super.update(entryUrl, entry); } catch (RedirectRequiredException e) { entryUrl = handleRedirectException(e); } catch (SessionExpiredException e) { handleSessionExpiredException(e); } return super.update(entryUrl, entry); } @Override public <E extends BaseEntry> E insert(URL feedUrl, E entry) throws IOException, ServiceException { try { return super.insert(feedUrl, entry); } catch (RedirectRequiredException e) { feedUrl = handleRedirectException(e); } catch (SessionExpiredException e) { handleSessionExpiredException(e); } return super.insert(feedUrl, entry); } @Override public <F extends BaseFeed> F getFeed(URL feedUrl, Class<F> feedClass, DateTime ifModifiedSince) throws IOException, ServiceException { try { return super.getFeed(feedUrl, feedClass, ifModifiedSince); } catch (RedirectRequiredException e) { feedUrl = handleRedirectException(e); } catch (SessionExpiredException e) { handleSessionExpiredException(e); } return super.getFeed(feedUrl, feedClass, ifModifiedSince); } @Override public void delete(URL entryUrl) throws IOException, ServiceException { try { super.delete(entryUrl); return; } catch (RedirectRequiredException e) { entryUrl = handleRedirectException(e); } catch (SessionExpiredException e) { handleSessionExpiredException(e); } super.delete(entryUrl); } /** * Handles a session expired exception by obtaining a new authentication * token and updating the token in the request factory. */ private void handleSessionExpiredException(SessionExpiredException sessionExpired) throws SessionExpiredException, AuthenticationException { if (username != null && password != null) { String token = getAuthToken(username, password, null, null, serviceName, applicationName); GoogleGDataRequest.Factory factory = (GoogleGDataRequest.Factory) requestFactory; factory.setAuthToken(new UserToken(token)); } else { throw sessionExpired; } } /** * Handles a redirect exception by generating the new URL to use for the * redirect. */ private URL handleRedirectException(RedirectRequiredException redirect) throws ServiceException { try { return new URL(redirect.getRedirectLocation()); } catch (MalformedURLException e) { throw new ServiceException("Invalid redirected-to URL - " + redirect.getRedirectLocation()); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -