我正在尝试解决我的网络服务问题。 我已经在Java中阅读了关于outh2.0的所有文档并集成了Spreadsheet,我有3个问题。
我使用的Web应用程序包含jsp和Servlet文件。 我有一个表单,用户填写字段然后clic按钮提交。 然后它启动流程令牌。 如果第一次调用页面调用电子邮件,那么如果用户接受或取消访问权限,那么他们......我不知道控制任何东西。
1.-页面"回调",我需要多少方法?页面需要什么样的:JSP或html o Servlet?我不知道。 我知道在我的api控制台中,我配置(客户端ID,客户端密码,我可以下载文件json,授权JavaScript来源,授权重定向URI),但我不知道在我的代码中哪里可以看到它。 我在Java中有这个:
公共课SheetsQuickstart {
/** Application name. */
private static final String APPLICATION_NAME = "Name_APP";
/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(
System.getProperty("user.home"), "credentials/sheets.googleapis.com-java-quickstart");
/** Global instance of the {@link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;
/** Global instance of the scopes required by this quickstart.
*
* If modifying these scopes, delete your previously saved credentials
* at ~/.credentials/sheets.googleapis.com-java-quickstart
*/
private static final List<String> SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS_READONLY);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
* @return an authorized Credential object.
* @throws IOException
*/
public static Credential authorize() throws IOException {
/** Load client secrets.
* */
InputStream in = new FileInputStream("\client_secret.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();
Credential credential = new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
/**
* Build and return an authorized Sheets API client service.
* @return an authorized Sheets API client service
* @throws IOException
*/
public static Sheets getSheetsService() throws IOException {
Credential credential = authorize();
return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
public static void main(String[] args) throws IOException {
// Build a new authorized API client service.
Sheets service = getSheetsService();
// Prints the names and majors of students in a sample spreadsheet:
String spreadsheetId = "Id spreadsheet";
String range = "A4:C6";
ValueRange response = service.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
List<List<Object>> values = response.getValues();
if (values == null || values.size() == 0) {
System.out.println("No data found.");
} else {
System.out.println("Name, Major");
for (List<?> row : values) {
// Print columns A and E, which correspond to indices 0 and 4.
System.out.printf("%s, %s\n", row.get(0), row.get(1), row.get(2));
}
}
}
}
我有我的文件json,没关系。 我没有看到我需要在哪里看到access_toke或我如何得到它。
有人有这方面的例子还是可以帮助我?
感谢!!!!
答案 0 :(得分:0)
解决。这里放了我的代码。
公共类ServletOAuth2Callback扩展了HttpServlet {
private static final long serialVersionUID = 1L;
public static String GOOGLE_CLIENT_ID = "";
public static String GOOGLE_CLIENT_SECRET = "";
public ServletOAuth2Callback() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String stateP = request.getParameter("state");
System.out.println("stateP --> " +stateP);
/** No funciona */
String error = request.getParameter("error");
if(error != null){
System.out.println("");
String volverAJsp = "";
response.sendRedirect(volverAJsp);
}
else{
System.out.println("El usuario ha aceptado el acceso");
String code = request.getParameter("code");
System.out.println("code --> " +code);
GoogleAuthorizationCodeFlow flujo = null;
flujo = AutorizacionOAuth2.newFlow();
System.out.println("Flujo string --> " +flujo.toString());
System.out.println("Flujo token encodeurl --> " +flujo.getTokenServerEncodedUrl());
System.out.println("Flujo access_type --> " +flujo.getAccessType()); //ahora mismo es null
System.out.println("Flujo client_id --> " +flujo.getClientId());
System.out.println("Flujo scopes as string --> " +flujo.getScopesAsString());
System.out.println("Flujo nuevo token --> " +flujo.newTokenRequest(code));
GoogleTokenResponse token = null;
token = AutorizacionOAuth2.requestAccessToken(flujo, code);
//System.out.println("Token toString --> " +token.toString());
System.out.println("Token access --> " +token.getAccessToken());
System.out.println("Token expire --> " +token.getExpiresInSeconds());
System.out.println("Token type --> " +token.getTokenType());
String urlSsSession = (String) request.getSession().getAttribute("URL");
System.out.println("La UrlSsSession --> " +urlSsSession);
String idHoja = urlSsSession.substring(39, 83);
System.out.println("idHoja --> " +idHoja);
Sheets service = AutorizacionOAuth2.getSheetsService(flujo, token);
System.out.println("Servicio string --> " +service.toString());
System.out.println("Servicio name --> " +service.getApplicationName());
System.out.println("Servicio sheets --> " +service.spreadsheets().sheets().toString());
String spreadsheetId = idHoja;
String range = "A4:C";
System.out.println("Spreadsheet --> " +spreadsheetId.toString());
System.out.println("range --> " +range);
Get respuesta = service.spreadsheets().values()
.get(spreadsheetId, range);
System.out.println("Get respuesta --> " +respuesta.toString());
System.out.println("Exe respuesta --> " +respuesta.execute());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("----------------------------------------------------------");
System.out.println("Estamos en el metodo doPost() en la clase SOAuth2Callback.");
String urlSpreadsheet = request.getParameter("URL");
System.out.println("La URL del text --> " +urlSpreadsheet);
request.getSession().setAttribute("URL", urlSpreadsheet);
String variable = AutorizacionOAuth2.getOauthUrlGoogle(request, urlSpreadsheet);
System.out.println("Metodo getOauthUrlGoogle--> " +variable);
String estado = request.getSession().getId();
System.out.println("estado --> " +estado);
response.sendRedirect(variable);
}
public class AutorizacionOAuth2 {
private static String CLIENT_ID = "";
private static final String SCOPE = "https://www.googleapis.com/auth/drive";
private static final List<String> SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS, SheetsScopes.DRIVE);
private static final String APPLICATION_NAME = "";
private static FileDataStoreFactory DATA_STORE_FACTORY = null;
private static HttpTransport HTTP_TRANSPORT = null;
private static JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static String client_id = "";
private static String client_secret = "";
private static String redirectUrl = "";
private static java.io.File DATA_STORE_DIR = new java.io.File(
System.getProperty("user.home"), "credentials/creden_json/");
public static String getCallbackUrl() {
System.out.println("Estamos en el metodo getCallbackUrl() en la clase AutorizacionOAuth2.");
String redirectUrl = "";
return redirectUrl;
}
public static GoogleTokenResponse requestAccessToken(AuthorizationCodeFlow flow, String code) throws IOException, GoogleJsonResponseException {
System.out.println("Estamos en el metodo requestAccessToken() en la clase AutorizacionOAuth2.");
return (GoogleTokenResponse) flow.newTokenRequest(code).setRedirectUri("http://localhost:8080/appweb/ServletOAuth2Callback").execute();
}
public static String getOauthUrlGoogle(HttpServletRequest request, String urlSpreadsheet) {
System.out.println("Estamos en el metodo getOauthUrlGooglePrueba() en la clase AutorizacionOAuth2.");
StringBuilder oauthUrl = new StringBuilder();
oauthUrl.append("https://accounts.google.com/o/oauth2/auth")
.append("?client_id=").append(CLIENT_ID) //the client id from the api console registration
.append("&response_type=code")
.append("&scope=").append(SCOPE) //scope is the api permissions we are requesting
.append("&redirect_uri=").append(redirectUrl) //the servlet that google redirects to after authorization
.append("&state=").append(request.getSession().getId())//ID de la sesion del usuario
.append("&urlSpreadsheet=").append(urlSpreadsheet);
return oauthUrl.toString();
}
public static GoogleAuthorizationCodeFlow newFlow() throws IOException{
System.out.println("Estamos en el metodo GoogleAuthorizationCodeFlow() en la clase AutorizacionOAuth2.");
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
}
catch (Throwable t) {
System.out.println("Ha fallado la ruta de DATA_STORE_DIR");
t.printStackTrace();
//System.exit(1);
}
return new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
client_id, client_secret, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setApprovalPrompt("force")
.setAccessType("offline")
.build();
}
public static Sheets getSheetsService(GoogleAuthorizationCodeFlow flujo, GoogleTokenResponse token) throws IOException {
System.out.println("Estamos en el metodo getSheetsService() en la clase AutorizacionOAuth2.");
try{
GoogleCredential credential = AutorizacionOAuth2.autorizar(flujo);
credential.setFromTokenResponse(token);
credential.refreshToken();
System.out.println("Ya tenemos la credenciales en la variable credential.");
return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
catch(IOException io){
System.out.println("Estamos en la excepcion");
io.getMessage();
return null;
}
}
public static GoogleCredential autorizar(GoogleAuthorizationCodeFlow flujo) throws IOException {
System.out.println("Estamos en el metodo autorizar() en la clase AutorizacionOAuth2.");
InputStream clientSecretReader = new FileInputStream("");
GoogleClientSecrets clientSecrets = GoogleClientSecrets
.load(JSON_FACTORY, new InputStreamReader(clientSecretReader));
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setClientSecrets(clientSecrets)
.build();
System.out.println("Credentials guardadas en " + DATA_STORE_DIR.getAbsolutePath());
System.out.println("Credenciales --> " +credential.toString());
return credential;
}