使用Java发布到GoogleGroups API时出现Http 401错误?

时间:2019-05-30 22:24:33

标签: java api google-groups

Google API网站上的文档未包含有关使用groups api访问或修改组(例如添加成员)的完整示例。各个部分都有摘要,但将它们放在一起时却出现401错误,我不知道是否遗漏了一些关键部分。

我曾尝试将找到的代码片段放到可以正常运行的应用程序中,但出现401错误。

        GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("<path to my json file I downloaded from the service accounts page>"))
                .createScoped(Collections.singleton("https://www.googleapis.com/auth/admin.directory.group"));

        URL url = new URL("https://www.googleapis.com/admin/directory/v1/groups/<identifier to the group, such as the group email address>/members");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "Bearer " + credential.getAccessToken());
        conn.setRequestProperty("Accept", "application/json");

        StringBuffer jsonParamsBuffer = new StringBuffer();

        jsonParamsBuffer    .append("{")
                .append("\"email\": \"")
                .append("test-email@notarealdomain.fake")
                .append("\", ")
                .append("\"role\": \"")
                .append("MEMBER")
                .append("\"")
                .append("}")
                .append("]")
                .append("}");

        OutputStream os = conn.getOutputStream();
        os.write(jsonParamsBuffer.toString().getBytes());
        os.flush();

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        System.out.println("Response from Google Groups APi:");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

服务器返回HTTP响应代码:401,URL:https://reactjs.org/docs/composition-vs-inheritance.html / members

0 个答案:

没有答案