Issue
Currently In my android project I am using GeneratePresignedUrl to get the link of a private file from Amazon s3. it worked fine few times on main thread, after it started giving NetworkOnMainThreadException. My question is does GeneratePresignedUrl needs Asynctask? Or is it a bug ?
Android Aws sdk version 2.2.20 (new version).
Code: from 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;
}
Calling Above method like this.
URL url = Util.getSignedUrl(getContext().getApplicationContext(),"image path string");
It worked really fine 20+ times. And later started reporting NetworkOnMainThreadException.
Solution
AmazonS3.generatePresignedUrl itself doesn't make network request. However to create a presigned Url, it needs credentials from AmazonS3 client, and credentials are provided from CognitoCacheingCredentialsProvider which makes a network calls to STS and Cognito Identity Service. That's the cause of NetworkOnMainThreadException. If credentials are cached from previous calls, then such exception won't be thrown. Hope this explains.
Answered By - Yangfan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.