简体   繁体   中英

Getting Access token using Oauth2 with standalone java application

I am trying to use Google drive's APIs to develop a standalone java application(using only java SE). For that I need to get access token using Oauth2.0.For getting the access token I have written following code:

    package Drive;

    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;

    import static Drive.Constants.*;
    public class Test {

        public static void main(String[] args) throws IOException {

            String url=OAuth2URL+"redirect_uri=https://localhost/"+"&"+"client_id="+CLIENTID+"&"+"scope="+SCOPE+"&"+
                    "access_type=offline&"+"response_type=code";

            System.out.println("URL is :"+url);
            HttpClient httpClient= new DefaultHttpClient();
            HttpGet httpGet=new HttpGet(url);
            HttpResponse response=httpClient.execute(httpGet);
            if(response.getEntity().getContent()!=null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                String str = null;
                while ((str = reader.readLine()) != null) {
                    System.out.println(str);
                }
            }

        }
    }

I have put my credentials and oauth2.0 url in constant strings.My question is how can I get the response of this API call in to my application? Do I need to fork a listening process on specific port to get the response?

The redirect_uri should be registered on the google console (in the place you get your client_id ), and you should expose this url as a real http/s endpoint.

For more info see Step 2 Here: https://developers.google.com/identity/protocols/OAuth2InstalledApp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM