Reputation: 41
Can any one help us to run the URL through java code :
we are trying to upload a file from our local drive to Gmail Drive.
Steps Followed
Generated the URL with the help of Google Developer(API)
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList(DriveScopes.DRIVE))
.setAccessType("online")
.setApprovalPrompt("auto").build();
String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
Got the below URL
https://accounts.google.com/o/oauth2/auth?access_type=online&approval_prompt=auto&client_id=1066028402320.apps.googleusercontent.com&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&scope=https://www.googleapis.com/auth/drive
Run the URL in the internet browser
UserID and password is given as an input in the internet browser to get the unique response token
Now as a part of our development we have completed till step 2 and want to automate the steps 3 & 4 using java code. (After generating the URL provided with our UserdId and password we should get the response as unique token.)
Expecting your help on this
Upvotes: 4
Views: 533
Reputation: 2987
I would use the following scenario
Here are some more details with code.
Set up local webserver to retrieve HTTP request
Here is an example of setting local webserver with NanoHttpd
public class OAuthServer extends NanoHTTPD {
/**
* Constructs an HTTP server on given port.
*/
public DebugServer() {
super(8080);
}
@Override
public Response serve(String uri, Method method, Map<String, String> header, Map<String, String> parms, Map<String, String> files) {
bool error = false
string code = null
// User rejected approval
if (parm.containsKey("error")) {
error = true
}
// Here we get the code!
if (parm.containsKey("code")) {
code = parm.get("code")
}
StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<head><title>Authorization</title></head>");
sb.append("<body>");
if (error) {
sb.append("<h1>User rejected</h1>");
}
if (code==null) {
sb.append("<h1>Unknown Error</h1>");
}
else {
sb.append("<h1>Success</h1>");
}
sb.append("</body>");
sb.append("</html>");
return new Response(sb.toString());
}
public static void main(String[] args) {
ServerRunner.run(OAuthServer.class);
}
}
Set redirect_uri of the flow to be local webserver and get auth url
String url = flow.newAuthorizationUrl().setRedirectUri("http://localhost:8080").build();
Open browser of auth url for the user
// open the default web browser for the HTML page
Desktop.getDesktop().browse(url);
Retrieve code from local webserver and exchange oauth code
Now, user will approve OAuth from the web browser and send code to the local webserver we just started. Now that we have the code retrieved from local webserver, we can parse it into int and authenticate and authorize with it!
Hope this helps
Upvotes: 2