我的工作中,我想整合Google+的登入功能的Spring的MVC应用程序。 在此之前,有一些帮助的形式不错的人就这样,我成功地实现谷歌日历的功能。
现在,当我尝试使用Google+登录,我有2个选择,要么使用PHP代码,或JavaScript再加上一些其他后端选项。
我的观点是,谷歌日历的实现还需要授权用户,但我能做到这一点纯粹是在Java中,而我无法这样做,在Java中,我无法找到任何相关的代码。 我只是想调用Java方法,它在浏览器中打开一个新标签,用户点击接受,而且我重定向到URI(类似于谷歌日历,我会后下)
谁能帮我明白为什么只有代码,我发现在运行嵌入式服务器,我不能让它运行离不开它。 非常感谢。
日历代码:
public void authorizeAndTest(){
try {
httpTransport = new NetHttpTransport();
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);
Credential credential = authorize();
client = new com.google.api.services.calendar.Calendar.Builder(httpTransport,JSON_FACTORY,credential).setApplicationName(APPLICATION_NAME).build();
showCalenders();
addCalendarsUsingBatch();
Calendar calendar = addCalendar();
updateCalendar(calendar);
addEvent(calendar);
showEvents(calendar);
deleteCalendarInBatch();
deleteCalendar(calendar);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Credential authorize() throws Exception{
AuthorizationCodeFlow codeFlow = new GoogleAuthorizationCodeFlow(httpTransport,JSON_FACTORY,
"clientid",
"clientsecret", Collections.singleton(CalendarScopes.CALENDAR));
return new AuthorizationCodeInstalledApp(codeFlow,new LocalServerReceiver()).authorize("user@gmail.com");
}
现在,上面的代码工作就像一个魅力,我只是叫我控制方法,它调用authorizeAndTest,完全没有问题,它会打开一个标签,我点击接受,并开始处理。
欢迎使用Google+登录:下面的代码是从示例:
public static void main(String[] args) throws Exception {
Server server = new Server(4567);
ServletHandler servletHandler = new ServletHandler();
SessionHandler sessionHandler = new SessionHandler();
sessionHandler.setHandler(servletHandler);
server.setHandler(sessionHandler);
servletHandler.addServletWithMapping(ConnectServlet.class, "/connect");
servletHandler.addServletWithMapping(DisconnectServlet.class, "/disconnect");
servletHandler.addServletWithMapping(PeopleServlet.class, "/people");
servletHandler.addServletWithMapping(MainServlet.class, "/");
server.start();
server.join();
}
public static class MainServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// This check prevents the "/" handler from handling all requests by default
if (!"/".equals(request.getServletPath())) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.setContentType("text/html");
try {
// Create a state token to prevent request forgery.
// Store it in the session for later validation.
String state = new BigInteger(130, new SecureRandom()).toString(32);
request.getSession().setAttribute("state", state);
// Fancy way to read index.html into memory, and set the client ID
// and state values in the HTML before serving it.
response.getWriter().print(new Scanner(new File("index.html"), "UTF-8")
.useDelimiter("\\A").next()
.replaceAll("[{]{2}\\s*CLIENT_ID\\s*[}]{2}", CLIENT_ID)
.replaceAll("[{]{2}\\s*STATE\\s*[}]{2}", state)
.replaceAll("[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}",
APPLICATION_NAME)
.toString());
response.setStatus(HttpServletResponse.SC_OK);
} catch (FileNotFoundException e) {
// When running the quickstart, there was some path issue in finding
// index.html. Double check the quickstart guide.
e.printStackTrace();
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
response.getWriter().print(e.toString());
}
}
}
所以,我不能因为据我所知调用类的控制器,并在index.html的依赖是一个问题,所以我修改了代码一点。
GoogleSignin.java
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// This check prevents the "/" handler from handling all requests by default
if (!"/".equals(request.getServletPath())) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.setContentType("text/html");
try {
String state = new BigInteger(130, new SecureRandom()).toString(32);
request.getSession().setAttribute("state", state);
response.setStatus(HttpServletResponse.SC_OK);
} catch (Exception e) {
// When running the quickstart, there was some path issue in finding
// index.html. Double check the quickstart guide.
e.printStackTrace();
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
response.getWriter().print(e.toString());
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
String tokenData = (String) request.getSession().getAttribute("token");
System.out.println("Tokendata is "+tokenData);
if (tokenData != null) {
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().print(GSON.toJson("Current user is already connected."));
return;
}
if (!request.getParameter("state").equals(request.getSession().getAttribute("state"))) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().print(GSON.toJson("Invalid state parameter."));
return;
}
System.out.println("Request is "+request.toString());
ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
getContent(request.getInputStream(), resultStream);
String code = new String(resultStream.toByteArray(), "UTF-8");
try {
GoogleTokenResponse tokenResponse =
new GoogleAuthorizationCodeTokenRequest(TRANSPORT, JSON_FACTORY,
CLIENT_ID, CLIENT_SECRET, code, "postmessage").execute();
GoogleIdToken idToken = tokenResponse.parseIdToken();
String gplusId = idToken.getPayload().getSubject();
System.out.println("Response from google plus is "+gplusId);
request.getSession().setAttribute("token", tokenResponse.toString());
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().print(GSON.toJson("Successfully connected user."));
} catch (TokenResponseException e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().print(GSON.toJson("Failed to upgrade the authorization code."));
} catch (IOException e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
response.getWriter().print(GSON.toJson("Failed to read token data from Google. " +
e.getMessage()));
}
}
控制器代码是这样的:
@RequestMapping(value = "/authorize")
public String googleReplyManagment(HttpServletRequest request, HttpServletResponse response){
//OAuth oAuth = new OAuth();
//oAuth.authorizeAndTest();
response.setContentType("application/json");
GoogleSignIn googleSignIn = new GoogleSignIn();
try {
googleSignIn.doGet(request,response);
googleSignIn.doPost(request,response);
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/";
}
我得到以下错误:
错误代码 :
java.lang.NullPointerException
at com.journaldev.spring.utility.GoogleSignIn.doPost(GoogleSignIn.java:127)
at com.journaldev.spring.controller.PersonController.googleReplyManagment(PersonController.java:1453)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
我能做些什么这一点,任何帮助将是很好。 非常感谢。