ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

android – “code”:403,以及google plus上传文件中的“reason”:“禁止”异常

2019-10-04 19:25:58  阅读:260  来源: 互联网

标签:android file-upload google-plus


我试图在谷歌上传媒体文件,我已经在谷歌控制台创建了客户端ID.
我有上传方法表格
attaching-media

authentication

在运行应用程序时,我遇到异常

 Media result = null;
                    try {
                        result = insertRequest.execute();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        // e1.printStackTrace();
                        Log.e("result exception", "" + e1);
                    }

例外是:

 12-09 18:49:20.983: E/result exception(26301):com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
12-09 18:49:20.983: E/result exception(26301): {
12-09 18:49:20.983: E/result exception(26301):   "code" : 403,
12-09 18:49:20.983: E/result exception(26301):   "errors" : [ {
12-09 18:49:20.983: E/result exception(26301):     "domain" : "global",
12-09 18:49:20.983: E/result exception(26301):     "message" : "Forbidden",
12-09 18:49:20.983: E/result exception(26301):     "reason" : "forbidden"
12-09 18:49:20.983: E/result exception(26301):   } ],
12-09 18:49:20.983: E/result exception(26301):   "message" : "Forbidden"
12-09 18:49:20.983: E/result exception(26301): }

我的代码很震撼:

  public class MainActivity extends Activity {
public static final String CLIENT_ID = "***********************************";
public static final String CLIENT_SECRET = "******************************";
String REDIRECT_URI = "http://localhost";
//  String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
JsonFactory jsonFactory = new JacksonFactory();
String posturl ="https://www.googleapis.com/upload/plusDomains/v1/people/userId/media/collection";
HttpTransport transport = new NetHttpTransport();
GoogleTokenResponse tokenResponse;
@SuppressLint({ "NewApi", "SetJavaScriptEnabled" })
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.activity_main);
    WebView webview = new WebView(this);
    webview.setVisibility(View.VISIBLE);
    webview.getSettings().setJavaScriptEnabled(true);
    setContentView(webview);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();

    StrictMode.setThreadPolicy(policy);
    Collection<String> SCOPE = Arrays.asList(
            "https://www.googleapis.com/auth/plus.me",
            "https://www.googleapis.com/auth/plus.media.upload",
            "https://www.googleapis.com/auth/plus.stream.write");
    //      "https://www.googleapis.com/auth/plus.profiles.read");
    final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            transport, jsonFactory, CLIENT_ID,
            CLIENT_SECRET, SCOPE).setApprovalPrompt("force")
            .setAccessType("offline").build();

    String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI)
            .build();
    System.out.println("url:  " + url);
    webview.loadUrl(url);

    webview.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {

            if (url.startsWith(REDIRECT_URI)) {

                if (url.indexOf("code=") != -1) {
            // Url is like  http://localhost/?code=4/Z5DgC1IxNL-muPsrE2Sjy9zQn2pF
                    String code = url.substring(REDIRECT_URI.length() + 7,
                            url.length());

                    System.out.println("code:  " + code);
                    tokenResponse = null;
                    try {
                        tokenResponse = flow.newTokenRequest(code)
                                .setRedirectUri(REDIRECT_URI).execute();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    GoogleCredential credential =  new GoogleCredential.Builder()
                            .setTransport(transport)
                            .setJsonFactory(jsonFactory)
                            .setClientSecrets(CLIENT_ID, CLIENT_SECRET)
                            .addRefreshListener(
                                    new CredentialRefreshListener() {
                                        @Override
                                        public void onTokenResponse(
                                                Credential credential,
                                                TokenResponse tokenResponse) {
                                            System.out
                                                    .println("Credential was refreshed successfully.");
                                        }

                                        @Override
                                        public void onTokenErrorResponse(
                                                Credential credential,
                                                TokenErrorResponse tokenErrorResponse) {
                                            System.err
                                                    .println("Credential was not refreshed successfully. "
                                                            + "Redirect to error page or login screen.");
                                        }
                                    }).build();

                    credential.setFromTokenResponse(tokenResponse);

                    PlusDomains plusDomains = new PlusDomains.Builder(
                            transport, jsonFactory, credential).setApplicationName("RiskScore").build();

                    String userId = "me"; // Requires the plus.me scope
                    File jpegFile = null;
                      jpegFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/RiskScore/20131205115454.jpg");



                    Media mediaDescription = new Media();
                    mediaDescription.setDisplayName("A picture of Score");
                    Insert insertRequest = null;
                    try {
                        insertRequest = plusDomains.media().insert(userId,
                                "cloud", mediaDescription,
                                new FileContent("image/jpeg", jpegFile));
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        // e1.printStackTrace();
                        Log.e("insertRequest exception", "" + e1);
                    }

                    Media result = null;
                    try {
                        result = insertRequest.execute();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        // e1.printStackTrace();
                        Log.e("result exception", "" + e1);
                    }
                    if (result != null) {
                        String mediaId = result.getId();

                        // Now create a post using the uploaded image

                        // Create the activity and populate the contents
                        com.google.api.services.plusDomains.model.Activity activity = new com.google.api.services.plusDomains.model.Activity();
                        activity.setObject(new PlusDomainsObject());
                        activity.getObject().setContent("Risk Project....");

                        // Attach the photo
                        PlusDomainsObject.Attachments attachment = new PlusDomainsObject.Attachments();
                        attachment.setObjectType("photo"); 
                        attachment.setId(mediaId);
                        ArrayList<Attachments> attachments = new ArrayList<PlusDomainsObject.Attachments>();
                        attachments.add(attachment); 
                        // You can also add multiple attachments to the post
                        activity.getObject().setAttachments(attachments);

                        // Set the activity to be visible only to your domain
                        PlusDomainsAclentryResource acl = new PlusDomainsAclentryResource();
                        acl.setType("domain");
                        Acl aclEntries = new Acl();
                        aclEntries
                                .setItems(new ArrayList<PlusDomainsAclentryResource>());
                        aclEntries.getItems().add(acl);
                        aclEntries.setDomainRestricted(true); 
                        // Required, this does the domain restriction
                        activity.setAccess(aclEntries);

                        // Post the activity
                        com.google.api.services.plusDomains.model.Activity newActivity = null;
                        try {
                            newActivity = plusDomains.activities()
                                    .insert(userId, activity).execute();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        System.out.println("New activity created with ID "
                                + newActivity.getId());
                        System.out.println("URL: " + newActivity.getUrl());

                        view.setVisibility(View.INVISIBLE);
                    }
                } else if (url.indexOf("error=") != -1) {
                    view.setVisibility(View.INVISIBLE);
                }
            }
        }
    });

}

}

解决方法:

要使用Google Domains API,您需要确保代表您的用户的域已设置为具有适合您应用的权限.这些说明位于quick-start guide第1步的“为您的服务帐户授予域范围权限”部分.

具体而言,您需要将应用的客户端ID与您的应用在域控制面板中使用的范围相关联.域管理员是唯一可以执行此操作的人 – 因此,如果您正在使用其他域,请确保您与该人联系.此外,控制面板中列出的范围必须与您在应用中请求的范围完全匹配.

标签:android,file-upload,google-plus
来源: https://codeday.me/bug/20191004/1854221.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有