現在PC上で動くjavaのネイティブアプリで、googleアカウントでのログイン機能を実装しようとしています。
流れとして考えているのは
①ユーザがボタンを押すとブラウザを立ち上げ、アプリの許可のリクエストをする
②許可を押してもらい、アクセストークンを取得するためのcodeをブラウザ上に表示する
③codeをコピーしてもらいネイティブアプリに入力させる
④アクセストークンを取得し、googleアカウントのプロフィールを取得する
です
これをやっていまして、現在③まではできています。
しかし、入力してもらったcodeからアクセストークンを取得するところでエラーが出て取得できません。どうすればよろしいでしょうか。
以下にコードを抜粋したものとエラーを掲載します
(json形式で結果が返ってくると思うのですが、今回はreadLineで適当に受信しようとしています。ここに問題があるのでしょうか)
//codeには認証後にブラウザに表示されるcodeを入力しています
String poststr = "code="+code+"&"
+ "clent_id={client_idを入れています}&"
+ "client_secret={同様}&"
+ "redirect_uri=urn:ietf:wg:oauth:2.0:oob&"
+ "grant_type=authorization_code";
String urlString = "https://accounts.google.com/o/oauth2/token";
try {
URL url = new URL(urlString);
connection =(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(poststr));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); writer.write(poststr); writer.flush(); writer.close(); try (InputStreamReader isr = new InputStreamReader(connection.getInputStream()); BufferedReader reader = new BufferedReader(isr)) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); isr.close(); } } catch (IOException e) { System.err.println("Can't connect to " + urlString); System.exit(1); } finally{ if(connection !=null){ connection.disconnect(); } }
}
結果
Can't connect to https://accounts.google.com/o/oauth2/token
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。