本周我开发了一个小程序,我需要创建一个Web应用程序(在localhost上使用Java Servlet),这个Web App需要执行以下操作:
注意:我只能使用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");
}
...
我的问题出现在第三部分,我从谷歌得到响应代码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();
}
我已经待了几天了,但是由于其他项目也缩短了我的时间,我越来越难以找到问题,这就是我请求你的帮助的原因:)
提前致谢
答案 0 :(得分:0)
API将在返回401状态代码时指示访问令牌已过期。要获取新的访问令牌,请向令牌端点发出请求并包含client_id,client_secret,refresh_token和grant_type参数。
您可以在此link中找到更多信息。
希望有所帮助!