我正在使用Jersey客户端调用Google oauth作为令牌,如下所示。
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource webResource = client.resource(UriBuilder.fromUri("https://accounts.google.com/o/oauth2/token").build());
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("code", request.getParameter("code"));
formData.add("client_id", Global.GOOGLE_CLIENT_ID);
formData.add("redirect_uri", Global.GOOGLE_REDIRECT_URL);
formData.add("client_secret", Global.GOOGLE_SECRET);
formData.add("grant_type", "authorization_code");
ClientResponse response1 = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData);
System.out.println(response1.getEntity(String.class));
System.out.println(response1.getClass().getName());
我得到的回应
{“access_token”: “ya29.nQCXFIhTs8s-SQKON6NjPv7wkBcJxlasdlkjsdsklsGuzMMqyDz3XpkNLT”,
“token_type”:“Bearer”,“expires_in”:3599,“id_token”: “eyJhbGciOiJSUzI1NiIsImtpZCI6IjdkZGQwOGEwM2IyNWQwZjVhMDllMjNiMmJlMTBkZDIyODQyYTg1NjkifQ.eyJpc3MiOiJhY2NvdW50csdlksjdsdkljdslkjdsdslkjdjsdkljjsldkjsdj987230iOiJwcmVtMXByZUBnbWFpbC5jb20iLCJhdF9oYXNoIjoiMmt2RlZ1RUpTMGp4UWlIUDgtckVuZyIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJhdWQiOiI1OTQ5NTUyODE4ODYtYnFyMGRibWRyYWJxYW9ubWhlaXFrMHNrZGRmNWFsazUuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJpYXQiOjE0MTMyMTQ4ODIsImV4cCI6MTQxMzIxODc4Mn0.pc2Snmb4pRF_TqylBuEpz0oBoWZsIq-_r_sqLS06E6DJKgSawWCg_3vqtI72GvWno0J8UghZka6rpaoAFo5RZlxNxLDs4GV5rZqdodNgbKjEO-5MrpGZWUOM7SNoYooASesmTtbamDoCf6G74MSKW5XKaVwdvFEUsSBz5NuavNU”}
如何从响应中获取id_token并在响应中获取实际值。
答案 0 :(得分:1)
迄今为止实现的最简单的解决方案是使用JSONSerializer来获取字符串响应的JSONObject表示。代码看起来与此类似:
JSONObject jsonOutput = (JSONObject) JSONSerializer.toJSON( response.getEntity(String.class) );
String access_token = jsonOutput.getString("access_token");
String id_token = jsonOutput.getString("id_token");
我建议使用google java客户端拨打电话:https://code.google.com/p/google-api-java-client/wiki/OAuth2
使用GoogleAuthorizationCodeTokenRequest类,您可以直接取回GoogleResponseToken而无需担心JSON。示例如下:http://javadoc.google-api-java-client.googlecode.com/hg/1.18.0-rc/com/google/api/client/googleapis/auth/oauth2/GoogleAuthorizationCodeTokenRequest.html
代码就像这样简单(直接取自链接):
GoogleTokenResponse response =
new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(),
"812741506391.apps.googleusercontent.com", "{client_secret}",
"4/P7q7W91a-oMsCeLvIaQm6bTrgtp7", "https://oauth2-login-demo.appspot.com/code")
.execute();
System.out.println("Access token: " + response.getAccessToken());
System.out.println("Id token: " + response.getIdToken());