【发布时间】:2014-11-19 07:37:32
【问题描述】:
这周我有一个小程序要开发,我需要创建一个 Web 应用程序(使用本地主机上的 Java Servlet),这个 Web 应用程序需要执行以下操作:
- 从 GitHub 获取并显示来自公共组织的问题
- 通过 OpenID Connect(OAuth 2.0) 获得身份验证
- 使用 REST 从问题的默认任务列表中创建 Google 任务
注意:我只能使用 HTTP,没有 jar 库
第一部分很简单,只需要向 GitHub API 发出请求并解析 JSON,这里没问题
第二部分有点简单,我必须在 Google Developer Console 中创建一个新的客户端 ID,我会在其中设置回调并接收代码,我会把它放在这里以防万一有什么问题:
Login.java
...
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
System.out.println("--New login request was received --");
resp.setStatus(302);
resp.setHeader("Location", GoogleStuff.AUTH_LINK);
}
...
callback.java
...
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Cookie c = new Cookie("googleCode", req.getParameter("code")); c.setMaxAge(60*60); //1 Hour
//Example code received from Google
//4/6POIUYwZA3tFCnX_2feRDGiPMQOU7At8HyfOzemMkOY.wtiPpsElo8wZoiIBeR5Q2m9sqEaFkwI
resp.addCookie(c);
resp.setStatus(302);
resp.setHeader("Location","searchOrg");
}
...
我的问题出现在第三部分,我从 Google 获得响应代码 401(未授权),我确定我做错了什么,但我真的不知道哪里出了问题。这可能都是错误的,所以请耐心等待:p
注意:为了获取 API 密钥,我使用了 Google Developer Console 并为浏览器创建了一个密钥
GoogleStuff.java
...
public static String AUTH_LINK = "https://accounts.google.com/o/oauth2/auth?"+
"scope=https://www.googleapis.com/auth/tasks&"+
"redirect_uri=http://localhost:5005/callback&"+
"response_type=code&" +
"client_id=" + FirstHttpServer.CLIENT_ID +
"&approval_prompt=force";
...
public static void addTask(Issue i, String googleCode){
try {
String postURL = "https://www.googleapis.com/tasks/v1/lists/%40default/tasks?key=" + MyServer.API_KEY;
URL url = new URL(postURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", googleCode);
BufferedWriter httpRequestBodyWriter = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
httpRequestBodyWriter.write(i.toJson());
httpRequestBodyWriter.close();
Scanner httpResponseScanner = new Scanner(connection.getInputStream());
while(httpResponseScanner.hasNextLine())
System.out.println(httpResponseScanner.nextLine());
httpResponseScanner.close();
} catch (IOException e) {
System.out.println(e.toString());
throw new RuntimeException();
}
我已经做了几天了,但是由于其他项目也缩短了我的时间,我越来越难以找到这个问题,这就是我请求你帮助的原因:)
提前致谢
【问题讨论】:
-
我没有专业知识可以帮助您处理 Google 任务,但我发表评论欢迎您使用 StackOverflow 并在您的第一个问题上表扬您 - 您的格式很好,并证明您已尝试自己解决问题,干得好!
-
感谢您的好话,花了几分钟时间研究格式化以确保一切都易于理解。如果您要浪费一些时间来回答我的问题,我最好使用我的一些来使其对其他人尽可能容易。
标签: java rest oauth google-tasks