这周我有一个小程序要开发,我需要创建一个 Web 应用程序(使用本地主机上的 Java Servlet),这个 Web 应用程序需要执行以下操作:
- 从 GitHub 获取并显示来自公共组织的问题
- 通过 OpenID Connect(OAuth 2.0) 获取身份验证
- 使用 REST 从问题中的默认任务列表创建 Google 任务
注意:我只能使用 HTTP,没有 jar 库
第一部分很简单,只需要向 GitHub API 发出请求并解析 JSON,这里没问题
第二部分有点简单,我必须在谷歌开发者控制台中创建一个新的客户端 ID,在那里我设置回调并接收代码,我会把它放在这里以防万一我做错了什么它:
登录.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);
}
...
回调.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");
}
...
我的问题出现在第三部分,我从谷歌得到响应代码 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();
}
我已经做了几天了,但是随着其他项目也缩短了我的时间,我越来越难以找到这个问题,这就是我请求你帮助的原因:)
提前致谢