我正在尝试在我的一个应用程序中使用 Google+ 登录。我WebView
用于登录用户,在获取auth
令牌后,我想获取一些用户信息,如姓名、电子邮件地址等。
我知道AccountManager的场景。
但是,我希望用户使用 登录,而不是使用已经存储的帐户WebView
,并且在成功登录后,我希望他的电子邮件 ID 作为信息。
我正在尝试遵循短代码。但我得到401异常。java.io.IOException: Unauthorized
WebView webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://mail.google.com");
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
Log.d("Home", "Url :" + url);
String requestToken = "";
if (url.contains("auth=")) {
requestToken += url.substring(url.indexOf("auth=") + 5);
Log.d("Home", "Request Token : " + requestToken);
requestUrl = "https://www.googleapis.com/oauth2/v1/userinfo?access_token="
+ requestToken;
view.stopLoading();
new CustomThread().start();
}
}
public void onPageFinished(WebView view, String url) {
// Log.d("Home", "Url :" + url);
// Log.d("Home", view.getUrl());
}
});
public class CustomThread extends Thread {
@Override
public void run() {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpClient.execute(new HttpGet(requestUrl));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
Log.d("Home", "Response : " + out.toString());
CookieSyncManager.getInstance().sync();
// Get the cookie from cookie jar.
String cookie = CookieManager.getInstance().getCookie(
requestUrl);
if (cookie == null) {
Log.d("Home", "Cookie is Null");
return;
}
// Cookie is a string like NAME=VALUE [; NAME=VALUE]
String[] pairs = cookie.split(";");
for (int i = 0; i < pairs.length; ++i) {
String[] parts = pairs[i].split("=", 2);
// If token is found, return it to the calling activity.
if (parts.length == 2
&& parts[0].equalsIgnoreCase("oauth_token")) {
Log.d("Home", "Token :" + parts[1]);
}
}
} else {
Log.d("Home", "Error : " + statusLine.getStatusCode());
// Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}