任何人都可以帮助我们通过
java代码运行URL:
我们正在尝试将文件从本地驱动器上传到Gmail云端硬盘.
接下来的步骤
>在Google Developer(API)的帮助下生成URL
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();
>获得以下网址
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
>在Internet浏览器中运行URL
>在Internet浏览器中将UserID和密码作为输入提供,以获取唯一的响应令牌
现在作为我们开发的一部分,我们已经完成了第二步,并希望自动化步骤3和步骤3. 4使用java代码. (后
生成随UserdId和密码提供的URL我们应该将响应作为唯一令牌.)
期待你的帮助
最佳答案 我会使用以下方案
>设置本地Web服务器以从用户的oauth重定向中检索代码
>将流的redirect_uri设置为本地Web服务器并获取auth url
>为用户打开auth url浏览器
>从本地Web服务器检索代码并交换oauth代码
以下是代码的更多细节.
设置本地Web服务器以检索HTTP请求
以下是使用NanoHttpd设置本地Web服务器的示例
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);
}
}
将流的redirect_uri设置为本地Web服务器并获取auth url
String url = flow.newAuthorizationUrl().setRedirectUri("http://localhost:8080").build();
为用户打开auth url浏览器
// open the default web browser for the HTML page
Desktop.getDesktop().browse(url);
从本地Web服务器检索代码并交换oauth代码
现在,用户将从Web浏览器批准OAuth并将代码发送到我们刚刚启动的本地Web服务器.现在我们已经从本地Web服务器检索了代码,我们可以将其解析为int并进行身份验证并使用它进行授权!
希望这可以帮助