本文介绍如何使用防盗链。

为了防止您在OSS上的数据被其他人盗链而产生额外费用,您可以设置防盗链功能,包括以下参数:
  • Referer白名单。仅允许指定的域名访问OSS资源。
  • 是否允许空Referer。如果不允许空Referer,则只有HTTP或HTTPS header中包含Referer字段的请求才能访问OSS资源。

更多关于防盗链的介绍,请参见开发指南中的设置防盗链

设置防盗链

以下代码用于设置防盗链:

PutBucketRefererRequest request = new PutBucketRefererRequest();
request.setBucketName("yourBucketName");
//添加Referer白名单。Referer参数支持通配符星号(*)和问号(?)。
ArrayList<String> referers = new ArrayList<String>();
referers.add("http://example.com");
referers.add("http://www.*.com");
referers.add("http://www.?.com");
request.setReferers(referers);

OSSAsyncTask task = oss.asyncPutBucketReferer(request, new OSSCompletedCallback<PutBucketRefererRequest, PutBucketRefererResult>() {
    @Override
    public void onSuccess(PutBucketRefererRequest request, PutBucketRefererResult result) {
        OSSLog.logInfo("code: " + result.getStatusCode());
    }
    @Override
    public void onFailure(PutBucketRefererRequest request, ClientException clientException, ServiceException serviceException) {
        OSSLog.logError("error: "+serviceException.getRawMessage());
    }
});
task.waitUntilFinished();

获取防盗链信息

以下代码用于获取防盗链信息:

GetBucketRefererRequest request = new GetBucketRefererRequest();
request.setBucketName("yourBucketName");
OSSAsyncTask task = oss.asyncGetBucketReferer(request, new OSSCompletedCallback<GetBucketRefererRequest, GetBucketRefererResult>() {
    @Override
    public void onSuccess(GetBucketRefererRequest request, GetBucketRefererResult result) {
        // 获取存储空间Referer白名单列表。
        ArrayList<String> list = result.getReferers();
        for (String ref : list){
            OSSLog.logInfo("info: " + ref);
        }
    }
    @Override
    public void onFailure(GetBucketRefererRequest request, ClientException clientException, ServiceException serviceException) {
        OSSLog.logError("error: "+serviceException.getRawMessage());
    }
});
task.waitUntilFinished();

清空防盗链

以下代码用于清空防盗链:

PutBucketRefererRequest request = new PutBucketRefererRequest();
request.setBucketName("yourBucketName");
request.setAllowEmpty(true);
// 防盗链不能直接清空,需要新建一个允许空Referer的规则来覆盖之前的规则。
ArrayList<String> referers = new ArrayList<String>();

request.setReferers(referers);
OSSAsyncTask task = oss.asyncPutBucketReferer(request, new OSSCompletedCallback<PutBucketRefererRequest, PutBucketRefererResult>() {
    @Override
    public void onSuccess(PutBucketRefererRequest request, PutBucketRefererResult result) {
        OSSLog.logInfo("code: " + result.getStatusCode());

    }
    @Override
    public void onFailure(PutBucketRefererRequest request, ClientException clientException, ServiceException serviceException) {
        OSSLog.logError("error: "+serviceException.getRawMessage());

    }
});
task.waitUntilFinished();