get Token from google account - Android Account

Android examples for Account:Google Account

Description

get Token from google account

Demo Code


//package com.java2s;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.util.Log;

public class Main {
    public static String getToken(String email, String password)
            throws IOException {
        // Create the post data
        // Requires a field with the email and the password
        StringBuilder builder = new StringBuilder();
        builder.append("Email=").append(email);
        builder.append("&Passwd=").append(password);
        builder.append("&accountType=GOOGLE");
        builder.append("&source=Google-cURL-Example");
        builder.append("&service=ac2dm");

        // Setup the Http Post
        byte[] data = builder.toString().getBytes();
        URL url = new URL("https://www.google.com/accounts/ClientLogin");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setUseCaches(false);/*from w w w.j  a  v a  2s .  c  o m*/
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        con.setRequestProperty("Content-Length",
                Integer.toString(data.length));

        // Issue the HTTP POST request
        OutputStream output = con.getOutputStream();
        output.write(data);
        output.close();

        // Read the response
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                con.getInputStream()));
        String line = null;
        String auth_key = null;
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("Auth=")) {
                auth_key = line.substring(5);
                Log.e("AUTH", auth_key);
            }
        }

        // Finally get the authentication token
        // To something useful with it
        return auth_key;
    }
}

Related Tutorials