我能够使用OATH2从Google API响应中获取用户信息。但是我不知道如何单独获取这些响应。
响应我从Google API获得:*
Access token: ya29.AHES6ZQ3QxKxnfAzpZasdfd23423NuxJs29gMa39MXV551yMmyM5IgA
{
"id": "112361XXXXXXXXXXX",
"name": "Ansuman XX",
"given_name": "Ansuman",
"family_name": "Singh",
"link": "https://plus.google.com/XXXXXXXXXXXXXXXXX",
"gender": "male",
"birthday": "0000-03-18",
"locale": "en"
}
Original Token: ya29.AHES6ZQ3QxKxnfAzpZu0lYHYu8sdfsdafdgMa39MXV551yMmyM5IgA New Token: ya29.AHES6ZQ3QxKxnfdsfsdaYHYu8TNuxJs29gMa39MXV551yMmyM5IgA
,但我只需要" id"&"名称"定量保存在我的数据库表中。我该怎么做?
我通过使用以下代码获得了上述响应/输出。
public static void main(String[] args) throws IOException
{
-------------------------
-------------------------
-------------------------
String accessToken = authResponse.accessToken;
GoogleAccessProtectedResource access = new GoogleAccessProtectedResource(accessToken, TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, authResponse.refreshToken);
HttpRequestFactory rf = TRANSPORT.createRequestFactory(access);
System.out.println("Access token: " + authResponse.accessToken);
String url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + authResponse.accessToken;
final StringBuffer r = new StringBuffer();
final URL u = new URL(url);
final URLConnection uc = u.openConnection();
final int end = 1000;
InputStreamReader isr = null;
BufferedReader br = null;
isr = new InputStreamReader(uc.getInputStream());
br = new BufferedReader(isr);
final int chk = 0;
while ((url = br.readLine()) != null)
{
if ((chk >= 0) && ((chk < end)))
{
r.append(url).append('n');
}
}
System.out.print("");
System.out.println();
System.out.print(" "+ r ); //this is printing at once but i want them individually
access.refreshToken();
System.out.println("Original Token: " + accessToken + " New Token: " + access.getAccessToken());
}
好吧,您可以在整个结果的JSON对象上使用这样的JSON库(围绕简单性设计;示例在此处设计),也可以使用自己的Regex代码。类似以下内容可能适用于后者:
//.... other existing code
String pat = ""(.*)": "(.*)"";
Pattern pattern = Pattern.compile(pat);
Matcher matcher = null;
Map<String,String> map = new HashMap<String,String>();
while ((url = br.readLine()) != null) {
if ((chk >= 0) && ((chk < end))) {
matcher = pattern.matcher(url);
if(matcher.find()) {
map.put(matcher.group(1), matcher.group(2));
}
//r.append(url).append('n');
}
}
System.out.println(map.get("id"));
//... rest of code
库方法可能过于杀伤,但可能会处理数据类型的转换等。