gmail-apigoogle-oauthrefresh-tokengoogle-oauth-java-client

Gmail Oauth2 required accesstoken and refreshtoken using java


I want to create a java application which automatically send email, so i am using Ouath2, first I am trying to get accesstoken and refreshtoken with my clidet id and secret id but i am not able to get access token please suggest me on this. to get accesstoken and refreshtoken the bellow code given in stackoverflow but for me it is giving error and refresh token variable i have left blank in the code {params.put("refresh_token","");} I dont know what to put there.

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.ArrayList;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONException;
    import org.json.JSONObject;

    /**
     *
     * @author arahman9
     */
    public class Oauth2App {

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws JSONException {
            // TODO code application logic here
           String at =  getAccessToken();
            getAccessToken(at);
        }

        public static String getAccessToken(String refreshToken) throws JSONException {

            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
            try {
                String GOOGLE_CLIENT_ID = "xxxxxxxxxxx5lrrb78a44t1lt7moaies.apps.googleusercontent.com";
                String GOOGLE_CLIENT_SECRET = "xxxxxxxx2IZkp6Yi0sRI1";
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
                nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token"));
                nameValuePairs.add(new BasicNameValuePair("client_id", GOOGLE_CLIENT_ID));
                nameValuePairs.add(new BasicNameValuePair("client_secret", GOOGLE_CLIENT_SECRET));
                nameValuePairs.add(new BasicNameValuePair("refresh_token", refreshToken));
                post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                org.apache.http.HttpResponse response = client.execute(post);
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer buffer = new StringBuffer();
                for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                    buffer.append(line);
                }

                JSONObject json = new JSONObject(buffer.toString());
                String accessToken = json.getString("access_token");
                System.out.println(accessToken);
                return accessToken;

            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        public static String getAccessToken() {
            try {
                Map<String, Object> params = new LinkedHashMap<>();
                params.put("grant_type", "refresh_token");
                params.put("client_id","xxxxxxxxxlrrb78a44t1lt7moaies.apps.googleusercontent.com");
            params.put("client_secret","xxxxxxxxIZkp6Yi0sRI1");
            params.put("refresh_token","");

            StringBuilder postData = new StringBuilder();
                for (Map.Entry<String, Object> param : params.entrySet()) {
                    if (postData.length() != 0) {
                        postData.append('&');
                    }
                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                }
                byte[] postDataBytes = postData.toString().getBytes("UTF-8");

                URL url = new URL("https://accounts.google.com/o/oauth2/token");
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setDoOutput(true);
                con.setUseCaches(false);
                con.setRequestMethod("POST");
                con.getOutputStream().write(postDataBytes);

                BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuffer buffer = new StringBuffer();
                for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                    buffer.append(line);
                }

                JSONObject json = new JSONObject(buffer.toString());
                String accessToken = json.getString("access_token");
                return accessToken;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }
    }

Error

run:
java.net.UnknownHostException: accounts.google.com
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:579)
    at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:625)
    at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:160)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
    at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:275)
    at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:371)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:933)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1092)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
    at oauth2app.Oauth2App.getAccessToken(Oauth2App.java:98)
    at oauth2app.Oauth2App.main(Oauth2App.java:37)
java.net.UnknownHostException: accounts.google.com
    at java.net.InetAddress.getAllByName0(InetAddress.java:1252)
    at java.net.InetAddress.getAllByName(InetAddress.java:1164)
    at java.net.InetAddress.getAllByName(InetAddress.java:1098)
    at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.resolveHostname(DefaultClientConnectionOperator.java:263)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:162)
    at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:326)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:610)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:445)
    at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:835)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at oauth2app.Oauth2App.getAccessToken(Oauth2App.java:55)
    at oauth2app.Oauth2App.main(Oauth2App.java:38)
BUILD SUCCESSFUL (total time: 1 second)

New Error

java.io.IOException: Server returned HTTP response code: 400 for URL: https://accounts.google.com/o/oauth2/v2/auth
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at oauth2.Oauthmain.getAccessToken(Oauthmain.java:99)
    at oauth2.Oauthmain.main(Oauthmain.java:36)
Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at character 1
    at org.json.JSONTokener.syntaxError(JSONTokener.java:413)
    at org.json.JSONObject.<init>(JSONObject.java:180)
    at org.json.JSONObject.<init>(JSONObject.java:420)
    at oauth2.Oauthmain.getAccessToken(Oauthmain.java:61)
    at oauth2.Oauthmain.main(Oauthmain.java:37)

Solution

  • The actual problem is with your proxy. It'll work with your mobile network.

    New error StatusCode->400 means you are sending a bad request. You need to send payload in form of JSON. You are sending payload in wrong format. Use some JSON converter and convert your data to JSON before sending.

    StringBuilder postData = new StringBuilder();
                for (Map.Entry<String, Object> param : params.entrySet()) {
                    if (postData.length() != 0) {
                        postData.append('&');
                    }
                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                }
                byte[] postDataBytes = postData.toString().getBytes("UTF-8");
    

    That code must be changed for JSON converter


    If you are under any proxy try connecting to another network without any proxy.


    Try changing authorization endpoint to v2 endpoint https://accounts.google.com/o/oauth2/v2/auth

    The authorize endpoint you are trying to hit is old one. So try with v2