在中设置上下文路径,同时授权应用程序使用java访问google API
我正在尝试使用java和spring访问google日历API。我成功地在eclipse中google插件提供的web应用程序环境上运行了一个示例项目。然而,当我尝试在Apache上运行相同的项目时,我遇到了许多问题。我有一个特别的疑问,它阻碍了我在项目上的进展。我无法创建在google app engine上注册的应用程序中定义的重定向url。在api中使用新的LocalServerReceiver() 返回新的AuthorizationCodeInstalledApp(流,新的LocalServerReceiver())。授权(“用户”) 创建一个urlshttp://localhost:/Callback 此URL与注册的URL不匹配 这会导致一个错误 使用localserverreceiver的构建器api 新的LocalServerReceiver().setport(8080).setHostname(“localhost/Oauthv2/oauth2callback”)也会导致错误sayig unknown hostname 任何人都可以帮助使重定向uri与在中设置上下文路径,同时授权应用程序使用java访问google API,java,spring,Java,Spring,我正在尝试使用java和spring访问google日历API。我成功地在eclipse中google插件提供的web应用程序环境上运行了一个示例项目。然而,当我尝试在Apache上运行相同的项目时,我遇到了许多问题。我有一个特别的疑问,它阻碍了我在项目上的进展。我无法创建在google app engine上注册的应用程序中定义的重定向url。在api中使用新的LocalServerReceiver() 返回新的AuthorizationCodeInstalledApp(流,新的LocalSe
@RequestMapping(“/checklogin”)
public@ResponseBody字符串newcallback(
HttpServletRequest请求、HttpServletResponse响应)引发IOException、GeneralSecurityException{
字符串消息=“
”
+“*********您好,来自plus示例servlet,Spring MVC教程此消息来自CrunchifyHelloWorld.java*********
”;
字符串应用程序\u NAME=“PlusSample”;
java.io.File数据\存储\目录=
新的java.io.File(System.getProperty(“user.home”),“.store/plus_sample”);
FileDataStoreFactory dataStoreFactory=新的FileDataStoreFactory(DATA_STORE_DIR);;
//设置HTTP传输和JSON工厂
HttpTransport HttpTransport=GoogleNetHttpTransport.newTrustedTransport();
JsonFactory JsonFactory=JacksonFactory.getDefaultInstance();
//加载客户端机密
GoogleClientSecrets clientSecrets=GoogleClientSecrets.load(jsonFactory,
新的InputStreamReader(BaseController.class.getResourceAsStream(“/client\u secrets.json”);
//设置授权代码流
GoogleAuthorizationCodeFlow=新建GoogleAuthorizationCodeFlow.Builder(
httpTransport、JSON_工厂、客户机密、,
Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory)
.build();
//授权
//http://localhost:8080/counterwebapp/oauth2callback
//LocalServerReceiver=新建LocalServerReceiver.Builder().setHost(“http://localhost:8080/counterwebapp/oauth2callback).setPort(8080.build();
LocalServerReceiver=新的LocalServerReceiver.Builder().setPort(8080.build();
凭证=
新授权代码InstalledApp(流量、接收器)。授权(“用户”);
//设置主Google+类
Plus Plus=新的Plus.Builder(httpTransport、jsonFactory、凭证)
.setApplicationName(“SpringAPI演示”)
.build();
//请求访问您的配置文件并将其显示到控制台
Person profile=plus.people().get(“me”).execute();
/*System.out.println(“ID:+profile.getId());
System.out.println(“名称:”+profile.getDisplayName());
System.out.println(“图像URL:+profile.getImage().getUrl());
System.out.println(“配置文件URL:+Profile.getUrl())*/
debug(“ID:,profile.getId());
debug(“Name:,profile.getDisplayName());
debug(“[welcomeName]计数器:{},++计数器);
返回视图索引;
//----凭证凭证=authFlow.loadCredential(Utils.getUserId(req));
}
我通过使用另一套API解决了这个问题。我无法理解新的localserverreceiver()api。此外,作为一名天真的web开发人员,我没有正确的基本基础,这使我陷入了进退两难的境地。无论如何,对于一些和我处境相似的人来说,下面的代码会很有用。我希望google能够以类似的方式记录OAuth2的JavaAPI
@RequestMapping("/simplelogin")
public @ResponseBody void simplemethod(
HttpServletRequest request, HttpServletResponse response) throws IOException, GeneralSecurityException{
String REDIRECT_URI = "http://localhost:8080/counterwebapp/redirect";
HttpTransport httpTransport=new NetHttpTransport();
JsonFactory jsonFactory=new JacksonFactory();
final Collection<String> SCOPE = Arrays.asList("https://www.googleapis.com/auth/userinfo.profile;https://www.googleapis.com/auth/userinfo.email;https://www.googleapis.com/auth/calendar".split(";"));
GoogleAuthorizationCodeFlow flow=new GoogleAuthorizationCodeFlow.Builder(httpTransport,jsonFactory,CLIENT_ID,CLIENT_SECRET,SCOPE).setAccessType("online").setApprovalPrompt("auto").build();
//GoogleAuthorizationCodeFlow flow=new GoogleAuthorizationCodeFlow.Builder(httpTransport,jsonFactory,CLIENT_ID,CLIENT_SECRET,Collections.singleton(CalendarScopes.CALENDAR)).setAccessType("online").setApprovalPrompt("auto").build();
String url=flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
System.out.println("Please open the following URL in your browser then type the authorization code:");
System.out.println(" " + url);
response.sendRedirect(
flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build());
return;
}
@RequestMapping("/redirect")
@ResponseBody String CallSampleServlet_sub(
HttpServletRequest request, HttpServletResponse response) throws IOException{
final String USER_INFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo";
GoogleAuthorizationCodeFlow authFlow = Utils.initializeFlowCalendar();
HttpTransport httpTransport=new NetHttpTransport();
JsonFactory jsonFactory=new JacksonFactory();
String code= request.getParameter("code");
System.out.println("code "+ code);
final Collection<String> SCOPE = Arrays.asList("https://www.googleapis.com/auth/userinfo.profile;https://www.googleapis.com/auth/userinfo.email;https://www.googleapis.com/auth/calendar".split(";"));
GoogleAuthorizationCodeFlow flow=new GoogleAuthorizationCodeFlow.Builder(httpTransport,jsonFactory,CLIENT_ID,CLIENT_SECRET,Collections.singleton(CalendarScopes.CALENDAR)).setAccessType("online").setApprovalPrompt("auto").build();
//GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, SCOPE).build();
GoogleTokenResponse resp
=flow.newTokenRequest(code).setRedirectUri("http://localhost:8080/counterwebapp/redirect").execute();
System.out.println((resp.getAccessToken()));
//GoogleCredential credential=new GoogleCredential().setFromTokenResponse(resp);
GoogleTokenResponse resp2 = new GoogleTokenResponse();
resp2.setAccessToken(resp.getAccessToken());
final Credential credential = flow.createAndStoreCredential((TokenResponse) resp2, null);
System.out.println("credential created: "+ credential);
com.google.api.services.calendar.Calendar service = new com.google.api.services.calendar.Calendar.Builder(
httpTransport, jsonFactory, credential)
.setApplicationName("Spring API Demo")
.build();
System.out.println("<h1>HELLO WORLD Prafull</h1>");
DateTime now = new DateTime(System.currentTimeMillis());
System.out.println("<h2>" + service.getApplicationName() + "</h2>");
CalendarList feed = service.calendarList().list().execute();
Events even = service.events().list("primary").setMaxResults(10).setTimeMin(now).setOrderBy("startTime").setSingleEvents(true).execute();
com.google.api.services.calendar.model.Events events = service.events().list("primary")
.setMaxResults(10)
.setTimeMin(now)
.setOrderBy("startTime")
.setSingleEvents(true)
.execute();
System.out.println("No upcoming events first found.");
List<Event> items = events.getItems();
if (items.size() == 0) {
System.out.println("No upcoming events found.");
} else {
System.out.println("Upcoming events");
for (Event event : items) {
DateTime start = event.getStart().getDateTime();
if (start == null) {
start = event.getStart().getDate();
}
System.out.printf("%s (%s)\n", event.getSummary(), start);
}
}
final HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
// Make an authenticated request
final GenericUrl url = new GenericUrl(USER_INFO_URL);
final HttpRequest req = requestFactory.buildGetRequest(url);
req.getHeaders().setContentType("application/json");
final String jsonIdentity = req.execute().parseAsString();
final String jsonIdentit1y = req.execute().parseAsString();
Oauth2 oauth2 = new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), credential).setApplicationName(
"Oauth2").build();
Userinfoplus userinfo = oauth2.userinfo().get().execute();
System.out.println(userinfo.toPrettyString());
com.google.appengine.repackaged.com.google.gson.Gson usergson = new com.google.appengine.repackaged.com.google.gson.Gson();
Userinfoplus user = usergson.fromJson(jsonIdentity, Userinfoplus.class);
System.out.println(user.getFamilyName()+ " "+ user.getGivenName()+ " "+ user.getEmail());
System.out.println(jsonIdentity);
return VIEW_INDEX;
}
@RequestMapping(“/simplelogin”)
public@ResponseBody void simplemethod(
HttpServletRequest请求、HttpServletResponse响应)引发IOException、GeneralSecurityException{
字符串重定向\u URI=”http://localhost:8080/counterwebapp/redirect";
HttpTransport HttpTransport=新的NetHttpTransport();
JsonFactory JsonFactory=新的JacksonFactory();
最终收集范围=Arrays.asList(“https://www.googleapis.com/auth/userinfo.profile;https://www.googleapis.com/auth/userinfo.email;https://www.googleapis.com/auth/calendar“.split(“;”);
GoogleAuthorizationCodeFlow=新建GoogleAuthorizationCodeFlow.Builder(httpTransport,jsonFactory,客户端ID,客户端机密,作用域)。setAccessType(“联机”).setApprovalPrompt(“自动”).build();
//GoogleAuthorizationCodeFlow=新建GoogleAuthorizationCodeFlow.Builder(httpTransport、jsonFactory、客户端ID、客户端密码、集合.singleton(CalendarScopes.CALENDAR)).setAccessType(“联机”).setApprovalPrompt(“自动”).build();
字符串url=flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI.build();
System.out.println(“请在浏览器中打开以下URL,然后键入授权代码:”);
System.out.println(“+url”);
response.sendRedirect(
flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI.build());
回来
}
@请求映射(“/redirect”)
@ResponseBody String CallSampleServlet_sub(
HttpServletRequest请求、HttpServletResponse响应)引发IOException{
最终字符串用户信息URL=”https://www.googleapis.com/oauth2/v1/userinfo";
GoogleAuthorizationCodeFlow authFlow=Utils.initializeFlowCalendar();
HttpTransport HttpTransport=新的NetHttpTransport();
JsonFactory JsonFactory=新的JacksonFactory();
字符串代码=request.getParameter(“代码”);
System.out.println(“代码”+代码);
最终收集范围=Arrays.asList(“https://www.googleapis.com/auth/userinfo.profile;https://www.googleapis.com/auth/userinfo.email;https://www.googleapis.com/auth/calendar“.split(“;”);
谷歌授权
@RequestMapping("/simplelogin")
public @ResponseBody void simplemethod(
HttpServletRequest request, HttpServletResponse response) throws IOException, GeneralSecurityException{
String REDIRECT_URI = "http://localhost:8080/counterwebapp/redirect";
HttpTransport httpTransport=new NetHttpTransport();
JsonFactory jsonFactory=new JacksonFactory();
final Collection<String> SCOPE = Arrays.asList("https://www.googleapis.com/auth/userinfo.profile;https://www.googleapis.com/auth/userinfo.email;https://www.googleapis.com/auth/calendar".split(";"));
GoogleAuthorizationCodeFlow flow=new GoogleAuthorizationCodeFlow.Builder(httpTransport,jsonFactory,CLIENT_ID,CLIENT_SECRET,SCOPE).setAccessType("online").setApprovalPrompt("auto").build();
//GoogleAuthorizationCodeFlow flow=new GoogleAuthorizationCodeFlow.Builder(httpTransport,jsonFactory,CLIENT_ID,CLIENT_SECRET,Collections.singleton(CalendarScopes.CALENDAR)).setAccessType("online").setApprovalPrompt("auto").build();
String url=flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
System.out.println("Please open the following URL in your browser then type the authorization code:");
System.out.println(" " + url);
response.sendRedirect(
flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build());
return;
}
@RequestMapping("/redirect")
@ResponseBody String CallSampleServlet_sub(
HttpServletRequest request, HttpServletResponse response) throws IOException{
final String USER_INFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo";
GoogleAuthorizationCodeFlow authFlow = Utils.initializeFlowCalendar();
HttpTransport httpTransport=new NetHttpTransport();
JsonFactory jsonFactory=new JacksonFactory();
String code= request.getParameter("code");
System.out.println("code "+ code);
final Collection<String> SCOPE = Arrays.asList("https://www.googleapis.com/auth/userinfo.profile;https://www.googleapis.com/auth/userinfo.email;https://www.googleapis.com/auth/calendar".split(";"));
GoogleAuthorizationCodeFlow flow=new GoogleAuthorizationCodeFlow.Builder(httpTransport,jsonFactory,CLIENT_ID,CLIENT_SECRET,Collections.singleton(CalendarScopes.CALENDAR)).setAccessType("online").setApprovalPrompt("auto").build();
//GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, SCOPE).build();
GoogleTokenResponse resp
=flow.newTokenRequest(code).setRedirectUri("http://localhost:8080/counterwebapp/redirect").execute();
System.out.println((resp.getAccessToken()));
//GoogleCredential credential=new GoogleCredential().setFromTokenResponse(resp);
GoogleTokenResponse resp2 = new GoogleTokenResponse();
resp2.setAccessToken(resp.getAccessToken());
final Credential credential = flow.createAndStoreCredential((TokenResponse) resp2, null);
System.out.println("credential created: "+ credential);
com.google.api.services.calendar.Calendar service = new com.google.api.services.calendar.Calendar.Builder(
httpTransport, jsonFactory, credential)
.setApplicationName("Spring API Demo")
.build();
System.out.println("<h1>HELLO WORLD Prafull</h1>");
DateTime now = new DateTime(System.currentTimeMillis());
System.out.println("<h2>" + service.getApplicationName() + "</h2>");
CalendarList feed = service.calendarList().list().execute();
Events even = service.events().list("primary").setMaxResults(10).setTimeMin(now).setOrderBy("startTime").setSingleEvents(true).execute();
com.google.api.services.calendar.model.Events events = service.events().list("primary")
.setMaxResults(10)
.setTimeMin(now)
.setOrderBy("startTime")
.setSingleEvents(true)
.execute();
System.out.println("No upcoming events first found.");
List<Event> items = events.getItems();
if (items.size() == 0) {
System.out.println("No upcoming events found.");
} else {
System.out.println("Upcoming events");
for (Event event : items) {
DateTime start = event.getStart().getDateTime();
if (start == null) {
start = event.getStart().getDate();
}
System.out.printf("%s (%s)\n", event.getSummary(), start);
}
}
final HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
// Make an authenticated request
final GenericUrl url = new GenericUrl(USER_INFO_URL);
final HttpRequest req = requestFactory.buildGetRequest(url);
req.getHeaders().setContentType("application/json");
final String jsonIdentity = req.execute().parseAsString();
final String jsonIdentit1y = req.execute().parseAsString();
Oauth2 oauth2 = new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), credential).setApplicationName(
"Oauth2").build();
Userinfoplus userinfo = oauth2.userinfo().get().execute();
System.out.println(userinfo.toPrettyString());
com.google.appengine.repackaged.com.google.gson.Gson usergson = new com.google.appengine.repackaged.com.google.gson.Gson();
Userinfoplus user = usergson.fromJson(jsonIdentity, Userinfoplus.class);
System.out.println(user.getFamilyName()+ " "+ user.getGivenName()+ " "+ user.getEmail());
System.out.println(jsonIdentity);
return VIEW_INDEX;
}