目前在我的android项目中,我正在使用GeneratePresignedUrlAmazon s3获取私有文件的链接。它在主线程上运行了好几次,在它开始发出NetworkOnMainThreadException之后。我的问题是GeneratePresignedUrl需要Asynctask吗?还是虫子?
android aws sdk版本2.2.20(新版本)。
代码:来自util.java

public static URL getSignedUrl(Context context,String imageString){
    URL url=null;

           try {
               System.out.println("Generating pre-signed URL.");
               java.util.Date expiration = new java.util.Date();
               long milliSeconds = expiration.getTime();
               milliSeconds += 1000 * 60 * 60; // Add 1 hour.
               expiration.setTime(milliSeconds);
                sGenerateSignedUrl = new GeneratePresignedUrlRequest(Constants.BUCKET, imageString);
                sGenerateSignedUrl.setMethod(HttpMethod.GET);
                sGenerateSignedUrl.setExpiration(expiration);
                url = getS3Client(context.getApplicationContext()).generatePresignedUrl(sGenerateSignedUrl);


                System.out.println("Pre-Signed URL = " + url.toString());
               //if(url!=null)
               return url;
           }catch (AmazonServiceException exception) {
                System.out.println("Caught an AmazonServiceException, " +
                        "which means your request made it " +
                        "to Amazon S3, but was rejected with an error response " +
                        "for some reason.");
                System.out.println("Error Message: " + exception.getMessage());
                System.out.println("HTTP  Code: " + exception.getStatusCode());
                System.out.println("AWS Error Code:" + exception.getErrorCode());
                System.out.println("Error Type:    " + exception.getErrorType());
                System.out.println("Request ID:    " + exception.getRequestId());
            } catch (AmazonClientException ace) {
                System.out.println("Caught an AmazonClientException, " +
                        "which means the client encountered " +
                        "an internal error while trying to communicate" +
                        " with S3, " +
                        "such as not being able to access the network.");
                System.out.println("Error Message: " + ace.getMessage());
            }


    return url;
}

像这样调用上面的方法。
URL url = Util.getSignedUrl(getContext().getApplicationContext(),"image path string");

它真的工作了20多次。后来开始报道。

最佳答案

AmazonS3.generatePresignedUrl本身不发出网络请求。但是,要创建预签名的url,它需要来自AmazonS3客户机的凭据,而来自CognitoCacheingCredentialsProvider的凭据则用于对sts和cognito身份服务进行网络调用。这就是NetworkOnMainThreadException的原因。如果从以前的调用缓存凭据,则不会引发此类异常。希望这能解释。

08-28 14:43