阿里云试用OSS的API获取某个文件文件的地址,返回的是http的地址,官方的示例代码如下:
String endpoint = "oss-cn-shanghai.aliyuncs.com"; OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); try { boolean exists = ossClient.doesObjectExist(bucketNameStatic, key); if (!exists) { return null; } Date expiration = new Date(new Date().getTime() + 3600 * 1000);//1小时有效期 URL url = ossClient.generatePresignedUrl(bucketNameStatic, key, expiration); return url.toString(); } finally { ossClient.shutdown(); }
如果从阿里云的后台看到的地址却是https的,现在一般都是https的地址了,所以也想办法获取到https地址,代码如下:
String endpoint = "oss-cn-shanghai.aliyuncs.com"; // 让生成的地址变成https ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setProtocol(Protocol.HTTPS); OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, clientBuilderConfiguration); try { boolean exists = ossClient.doesObjectExist(bucketNameStatic, key); if (!exists) { return null; } Date expiration = new Date(new Date().getTime() + 3600 * 1000);//1小时有效期 URL url = ossClient.generatePresignedUrl(bucketNameStatic, key, expiration); return url.toString(); } finally { ossClient.shutdown(); }
主要是使用ClientBuilderConfiguration设置协议为https,当然你也可以从返回的http地址,替换成https,但是不够优雅。不过如果要返回自定义域名的https地址,暂时还没有找到很好的方法,可能是需要试用string replace替换了。
文章评论