“401未经授权”试图通过Java API Client观看Google Drive上的更改时 [英] "401 Unauthorized" when trying to watch changes on Google Drive with Java API Client

查看:118
本文介绍了“401未经授权”试图通过Java API Client观看Google Drive上的更改时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

真的停留在这里。该代码由Google提供的示例构建:

  public static void main(String [] args){
try {
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(请在浏览器中打开以下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凭证=新的GoogleCredential()。setFromTokenResponse(response);

//创建一个新的授权API客户
Drive service = new Drive.Builder(httpTransport,jsonFactory,凭证).setApplicationName(Google Push)。build();

//插入一个文件
File body = new File();
body.setTitle(我的文档);
body.setDescription(测试文档);
body.setMimeType(text / plain);

java.io.File fileContent = new java.io.File(document.txt);
BufferedWriter bw = new BufferedWriter(new FileWriter(fileContent));
bw.write(allo !!!!);
bw.close();

System.out.println(file created? - >+ fileContent.createNewFile());
FileContent mediaContent = new FileContent(text / plain,fileContent);

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

watchChange(service,channelId,web_hook,https://clementlevallois.net/notifications); //行78

} catch(IOException ex){
Logger.getLogger(DriveCommandLine.class.getName()).log(Level.SEVERE,null,ex);



$ b private static Channel watchChange(Drive service,String channelId,String channelType,String channelAddress){

Channel channel =新频道();
channel.setId(channelId);
channel.setType(channelType);
channel.setAddress(channelAddress);
尝试{
return service.changes()。watch(channel).execute(); // line 91
} catch(IOException e){
e.printStackTrace();
}
返回null;
}

堆栈跟踪:

  com.google.api.client.googleapis.json.GoogleJsonResponseException:401未经授权
,位于com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException .java:145)
,位于com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
,位于com.google.api.client.googleapis.services .json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
,位于com.google.api.client.googleapis.services.AbstractGoogleClientRequest $ 1.interceptResponse(AbstractGoogleClientRequest.java:312)
,位于com.google。 api.client.http.HttpRequest.execute(HttpRequest.java:1049)
,位于com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
com。 google.api.client.googleapis.se rvices.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
at Controller.DriveCommandLine.watchChange( DriveCommandLine.java:91)
at Controller.DriveCommandLine.main(DriveCommandLine.java:78)


在调用Drive API时,API返回HTTP 401或HTTP 403响应。这些错误可能表示以下任何一项:

令牌过期,
令牌撤销(这会导致访问令牌和刷新令牌停止工作),
令牌未授权所需的作用域,
未通过OAuth 2.0协议正确授权请求。



令牌过期可以通过调用refreshToken()来处理。如果该呼叫失败并显示无效凭证


Really stuck here. The code, built from examples provided by Google:

public static void main(String[] args) {
    try {
        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:");
    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).setApplicationName("Google Push").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("document.txt");
    BufferedWriter bw = new BufferedWriter(new FileWriter(fileContent));
    bw.write("allo!!!!");
    bw.close();

    System.out.println("file created? -> " + fileContent.createNewFile());
    FileContent mediaContent = new FileContent("text/plain", fileContent);

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

    watchChange(service, "channelId", "web_hook", "https://clementlevallois.net/notifications"); // line 78

} catch (IOException ex) {
    Logger.getLogger(DriveCommandLine.class.getName()).log(Level.SEVERE, null, ex);
}

}

private static Channel watchChange(Drive service, String channelId, String channelType, String channelAddress) {

    Channel channel = new Channel();
    channel.setId(channelId);
    channel.setType(channelType);
    channel.setAddress(channelAddress);
    try {
        return service.changes().watch(channel).execute(); //line 91
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

The stack trace:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:312)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1049)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
    at Controller.DriveCommandLine.watchChange(DriveCommandLine.java:91)
    at Controller.DriveCommandLine.main(DriveCommandLine.java:78)

解决方案

API returning an HTTP 401 or HTTP 403 response when calling the Drive API. These errors could indicate any of:

Token expiry, Token revocation, (This would cause both the access token and the refresh token to stop working), Token not authorized for needed scopes, Request not authorized correctly with OAuth 2.0 protocol.

Token expiry can be handled by calling refreshToken(). If that call fails with an "Invalid Credentials"

这篇关于“401未经授权”试图通过Java API Client观看Google Drive上的更改时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆