如何从oauth获取用户名或电子邮件地址?

时间:2013-05-14 12:52:11

标签: android oauth gmail

我在我的Android应用程序中使用oAuth登录。我想在成功登录后提取用户名或电子邮件地址?有什么办法吗?如果是 - 如何?

我发现了这个:Extracting Gmail username with OAuth access token但实际上不知道如何使用它

1 个答案:

答案 0 :(得分:0)

好吧,我把互联网挖到最后,我想出了这个:

 private String usernameReader() {
        String jsonOutput = "";
        try {
            jsonOutput = makeSecuredReq(Constants.API_REQUEST, getConsumer(this.prefs));
            JSONObject jsonResponse = new JSONObject(jsonOutput);
            JSONObject m = (JSONObject) jsonResponse.get("feed");
            JSONObject email = (JSONObject) m.get("id");
            jsonOutput=email.getString("$t");
        } catch (Exception e) {
            Log.e("errroro", "Error executing request", e);
            //  console.setText("Error retrieving contacts : " + jsonOutput);
        }
        return jsonOutput;
    }

    private String makeSecuredReq(String url, OAuthConsumer consumer) throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        Log.i("Requesting", "Requesting URL : " + url);
        consumer.sign(request);
        HttpResponse response = httpclient.execute(request);
        Log.i("statusLine", "Statusline : " + response.getStatusLine());
        InputStream data = response.getEntity().getContent();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(data));
        String responeLine;
        StringBuilder responseBuilder = new StringBuilder();
        while ((responeLine = bufferedReader.readLine()) != null) {
            responseBuilder.append(responeLine);
        }
        // Log.i(C.TAG,"Response : " + responseBuilder.toString());
        return responseBuilder.toString();
    }

    private OAuthConsumer getConsumer(SharedPreferences prefs) {
        String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
        String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
        OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
        consumer.setTokenWithSecret(token, secret);
        return consumer;
    }

它只是这个http://androidwarzone.blogspot.com/2011/07/android-oauth-full-example-with-source.html

的略微修改版本 不过,谢谢William Carter的时间和精力。