我使用以下代码从Google plus获取用户信息, 但它有时会返回null。请告诉我这有什么问题或建议另一个代码。
private void fetchNameFromProfileServer() throws IOException, JSONException {
String token = fetchToken();
URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token="+token);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
int sc = con.getResponseCode();
if (sc == 200) {
InputStream is = con.getInputStream();
GOOGLE_USER_DATA = readResponse(is);
is.close();
System.out.println("Vr: In fetchNameFromProfileServer() of AbstractGetNameTask aync task.");
mActivity.finish();
Intent intent=new Intent(mActivity,Profile_Activity.class);
intent.putExtra("email_id", mEmail);
mActivity.startActivity(intent);
mActivity.finish();
return;
} else if (sc == 401) {
GoogleAuthUtil.invalidateToken(mActivity, token);
onError("Server auth error, please try again.", null);
return;
} else {
onError("Server returned the following error code: " + sc, null);
return;
}
}
private static String readResponse(InputStream is) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = new byte[2048];
int len = 0;
while ((len = is.read(data, 0, data.length)) >= 0) {
bos.write(data, 0, len);
}
return new String(bos.toByteArray(), "UTF-8");
}
答案 0 :(得分:2)
试试这段代码:
private void getProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = currentPerson.getDisplayName();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
Log.e(TAG, "Name: " + personName + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + email
+ ", Image: " + personPhotoUrl);
txtName.setText(personName);
txtEmail.setText(email);
// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ PROFILE_PIC_SIZE;
new LoadProfileImage(imgProfilePic).execute(personPhotoUrl);
} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
请参阅此链接enter link description here它可以帮助您