java - 从http ://localhost in java application获取授权码

标签 java google-drive-api

我正在开发一个应用程序,我将文件从我的应用程序同步到 GDrive,我已经阅读了开发人员支持的快速入门指南。我还可以使用示例代码上传文件。但我想摆脱谷歌返回的授权代码的复制/粘贴。在阅读了 stackoverflow 上的一些帖子后,我开始了解 redirect_uri ,我将其更改为 http://localhost 也在浏览器中获取身份验证代码,但我没有知道如何将其从浏览器获取到我的java应用程序。请指导我如何将身份验证代码从本地网络服务器获取到我的 java 应用程序。 提前致谢。祝所有开发者 friend 圣诞快乐。 这是我实现的代码。

public class CMDApp {

private static String CLIENT_ID = "CLIENT_ID";
private static String CLIENT_SECRET = "CLIENT_SECRET";

//private static String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
private static String REDIRECT_URI = "http://localhost/authCode";
 public static void main(String[] args) throws IOException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();

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();
System.out.println("Please open the following URL in your browser then type the authorization code:");
Desktop.getDesktop().browse(java.net.URI.create(url));

System.out.println("  " + url);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();

GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

//Create a new authorized API client
Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).build();

//Insert a file  
File body = new File();
body.setTitle("My document");
body.setDescription("A test document");
body.setMimeType("text/plain");

java.io.File fileContent = new java.io.File("D:\\Java GDrive Integration\\CMDApp\\src\\document.txt");
FileContent mediaContent = new FileContent("text/plain", fileContent);

File file = service.files().insert(body, mediaContent).execute();
System.out.println("File ID: " + file.getId());

} }

我想从浏览器获取此代码中的授权码。

最佳答案

您可以在 jsp 文件中使用 request.getParameter("code") 并在请求对象中设置 例如

<%
String authCode = request.getParameter("code");
request.setAttribute("authCode",authCode);
%>

你的服务器端就可以得到它

request.getAttribute("authCode");

关于java - 从http ://localhost in java application获取授权码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20740493/

相关文章:

java - 问题更新到 Glassfish 4.1

java - 是否可以在运行时(启动后)添加jar(使用web-fragment.xml)

php - 上传到团队驱动器的权限问题

java - 带有 Java 客户端库的 Google Drive V3 在 Android 上创建无标题文件

node.js - Nodejs 脚本不读取 GDOC 文件扩展名

java - 无法将 BLOB 转换为字符串

java - jsonObject as string - 搜索正则表达式以删除密码字段

方法签名中的 Java "params"?

apache - 使用 Google Drive Directory 作为 Apache 虚拟主机

android - 通过 Google Drive SDK 列出 Google Drive 中的所有可用文件