有奖捉虫:云通信与企业服务文档专题,速来> HOT

简介

本文档提供关于检索对象内容操作相关的 API 概览以及 SDK 示例代码。
API
操作名
操作描述
检索对象内容
从指定对象(CSV 格式或者 JSON 格式)中检索内容

简单操作

简单操作由 COSClient 类型发起请求,使用简单操作之前必须先创建一个 COSClient 实例。
COSClient 实例是并发安全的,这里推荐一个进程只创建一个 COSClient 实例,当不会再通过这个实例发起请求的时候,再选择关闭这个实例。

创建 COSClient

调用 COS 的接口之前,必须先创建一个 COSClient 的实例。
// 创建 COSClient 实例,这个实例用来后续调用请求
COSClient createCOSClient() {
// 设置用户身份信息。
// SECRETID 和 SECRETKEY 请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理
String secretId = System.getenv("secretId");//用户的 SecretId,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
String secretKey = System.getenv("secretKey");//用户的 SecretKey,建议使用子账号密钥,授权遵循最小权限指引,降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);

// ClientConfig 中包含了后续请求 COS 的客户端设置:
ClientConfig clientConfig = new ClientConfig();

// 设置 bucket 的地域
// COS_REGION 请参见 https://cloud.tencent.com/document/product/436/6224
clientConfig.setRegion(new Region("COS_REGION"));

// 设置请求协议, http 或者 https
// 5.6.53 及更低的版本,建议设置使用 https 协议
// 5.6.54 及更高版本,默认使用了 https
clientConfig.setHttpProtocol(HttpProtocol.https);

// 以下的设置,是可选的:

// 设置 socket 读取超时,默认 30s
clientConfig.setSocketTimeout(30*1000);
// 设置建立连接超时,默认 30s
clientConfig.setConnectionTimeout(30*1000);

// 如果需要的话,设置 http 代理,ip 以及 port
clientConfig.setHttpProxyIp("httpProxyIp");
clientConfig.setHttpProxyPort(80);

// 生成 cos 客户端。
return new COSClient(cred, clientConfig);
}

使用临时密钥创建 COSClient

如果要使用临时密钥请求 COS,则需要用临时密钥创建 COSClient。 本 SDK 并不能生成临时密钥,而需要使用额外的操作来生成,参见 临时密钥生成

// 创建 COSClient 实例,这个实例用来后续调用请求
COSClient createCOSClient() {
// 这里需要已经获取到临时密钥的结果。
// 临时密钥的生成参见 https://cloud.tencent.com/document/product/436/14048#cos-sts-sdk
String tmpSecretId = "TMPSECRETID";
String tmpSecretKey = "TMPSECRETKEY";
String sessionToken = "SESSIONTOKEN";

COSCredentials cred = new BasicSessionCredentials(tmpSecretId, tmpSecretKey, sessionToken);

// ClientConfig 中包含了后续请求 COS 的客户端设置:
ClientConfig clientConfig = new ClientConfig();

// 设置 bucket 的地域
// COS_REGION 请参见 https://cloud.tencent.com/document/product/436/6224
clientConfig.setRegion(new Region("COS_REGION"));

// 设置请求协议, http 或者 https
// 5.6.53 及更低的版本,建议设置使用 https 协议
// 5.6.54 及更高版本,默认使用了 https
clientConfig.setHttpProtocol(HttpProtocol.https);

// 以下的设置,是可选的:

// 设置 socket 读取超时,默认 30s
clientConfig.setSocketTimeout(30*1000);
// 设置建立连接超时,默认 30s
clientConfig.setConnectionTimeout(30*1000);

// 如果需要的话,设置 http 代理,ip 以及 port
clientConfig.setHttpProxyIp("httpProxyIp");
clientConfig.setHttpProxyPort(80);

// 生成 cos 客户端。
return new COSClient(cred, clientConfig);
}

检索对象内容

COS Select 支持检索以下格式的对象数据:
CSV 格式:对象以 CSV 格式存储,并以固定的分隔符划分。
JSON 格式:对象以 JSON 格式存储,可以是 JSON 文件或者 JSON 列表。
注意
使用 COS Select,您必须具有 cos:GetObject 的授权。
CSV、JSON 对象需要以 UTF-8 格式编码。
COS Select 支持检索 GZIP 或者 BZIP2 压缩的 CSV、JSON 对象。
COS Select 支持检索 SSE-COS 加密的 CSV、JSON 对象。

检索 CSV 格式

方法原型

public SelectObjectContentResult selectObjectContent(SelectObjectContentRequest selectRequest) throws CosClientException, CosServiceException {

请求示例

// 调用 COS 接口之前必须保证本进程存在一个 COSClient 实例,如果没有则创建
// 详细代码参见本页:简单操作 -> 创建 COSClient
COSClient cosClient = createCOSClient();

// 存储桶的命名格式为 BucketName-APPID,此处填写的存储桶名称必须为此格式
String bucketName = "examplebucket-1250000000";
// 对象键(Key)是对象在存储桶中的唯一标识。详情请参见 [对象键](https://cloud.tencent.com/document/product/436/13324)
String key = "exampleobject";

String query = "select s._1 from COSObject s";

SelectObjectContentRequest request = new SelectObjectContentRequest();
request.setBucketName(bucketName);
request.setKey(key);
request.setExpression(query);
request.setExpressionType(ExpressionType.SQL);

InputSerialization inputSerialization = new InputSerialization();
CSVInput csvInput = new CSVInput();
csvInput.setFieldDelimiter(",");
csvInput.setRecordDelimiter("\\n");
inputSerialization.setCsv(csvInput);
inputSerialization.setCompressionType(CompressionType.NONE);
request.setInputSerialization(inputSerialization);

OutputSerialization outputSerialization = new OutputSerialization();
outputSerialization.setCsv(new CSVOutput());
request.setOutputSerialization(outputSerialization);

final AtomicBoolean isResultComplete = new AtomicBoolean(false);
SelectObjectContentResult result = cosClient.selectObjectContent(request);
InputStream resultInputStream = result.getPayload().getRecordsInputStream(
new SelectObjectContentEventVisitor() {
@Override
public void visit(SelectObjectContentEvent.StatsEvent event)
{
System.out.println(
"Received Stats, Bytes Scanned: " + event.getDetails().getBytesScanned()
+ " Bytes Processed: " + event.getDetails().getBytesProcessed());
}
@Override
public void visit(SelectObjectContentEvent.EndEvent event)
{
isResultComplete.set(true);
System.out.println("Received End Event. Result is complete.");
}
}
);
BufferedReader reader = new BufferedReader(new InputStreamReader(resultInputStream));
StringBuffer stringBuffer = new StringBuffer();
String line;
while((line = reader.readLine())!= null){
stringBuffer.append(line).append("\\n");
}
System.out.println(stringBuffer.toString());
// 检查结果是否接受完整
if (!isResultComplete.get()) {
throw new Exception("result was incomplete");
}

// 确认本进程不再使用 cosClient 实例之后,关闭即可
cosClient.shutdown();

参数说明

参数名称
参数描述
类型
selectRequest
请求
SelectObjectContentRequest
SelectObjectContentRequest 成员说明:
参数名称
设置方法
描述
类型
bucketName
set 方法
Bucket 的命名格式为 BucketName-APPID ,详情请参见 命名规范
String
key
set 方法
指定分块上传到 COS 上的路径,即 对象键。例如对象键为 folder/picture.jpg
String
expression
set 方法
请求表达式
String
expressionType
set 方法
请求表达式类型
String
inputSerialization
set 方法
描述待检索对象的格式
InputSerialization
outputSerialization
set 方法
描述检索结果的输出格式
OutputSerialization

返回结果说明

成功:返回 InputStream。
失败:发生错误(如身份认证失败),抛出异常 CosClientException 或者 CosServiceException。详情请参见 异常处理

检索 JSON 格式

方法原型

public SelectObjectContentResult selectObjectContent(SelectObjectContentRequest selectRequest) throws CosClientException, CosServiceException {

请求示例

// 调用 COS 接口之前必须保证本进程存在一个 COSClient 实例,如果没有则创建
// 详细代码参见本页:简单操作 -> 创建 COSClient
COSClient cosClient = createCOSClient();

// 存储桶的命名格式为 BucketName-APPID,此处填写的存储桶名称必须为此格式
String bucketName = "examplebucket-1250000000";
// 对象键(Key)是对象在存储桶中的唯一标识。详情请参见 [对象键](https://cloud.tencent.com/document/product/436/13324)
String key = "exampleobject";

String query = "select * from COSObject s where mathScore > 85'";

SelectObjectContentRequest request = new SelectObjectContentRequest();
request.setBucketName(bucketName);
request.setKey(key);
request.setExpression(query);
request.setExpressionType(ExpressionType.SQL);

InputSerialization inputSerialization = new InputSerialization();
JSONInput jsonInput = new JSONInput();
jsonInput.setType(JSONType.LINES);
inputSerialization.setJson(jsonInput);
inputSerialization.setCompressionType(CompressionType.NONE);
request.setInputSerialization(inputSerialization);

OutputSerialization outputSerialization = new OutputSerialization();
outputSerialization.setJson(new JSONOutput());
request.setOutputSerialization(outputSerialization);

final AtomicBoolean isResultComplete = new AtomicBoolean(false);
SelectObjectContentResult result = cosClient.selectObjectContent(request);
InputStream resultInputStream = result.getPayload().getRecordsInputStream(
new SelectObjectContentEventVisitor() {
@Override
public void visit(SelectObjectContentEvent.StatsEvent event)
{
System.out.println(
"Received Stats, Bytes Scanned: " + event.getDetails().getBytesScanned()
+ " Bytes Processed: " + event.getDetails().getBytesProcessed());
}
@Override
public void visit(SelectObjectContentEvent.EndEvent event)
{
isResultComplete.set(true);
System.out.println("Received End Event. Result is complete.");
}
}
);
BufferedReader reader = new BufferedReader(new InputStreamReader(resultInputStream));
StringBuffer stringBuffer = new StringBuffer();
String line;
while((line = reader.readLine())!= null){
stringBuffer.append(line).append("\\n");
}
System.out.println(stringBuffer.toString());
// 检查结果是否接受完整
if (!isResultComplete.get()) {
throw new Exception("result was incomplete");
}

// 确认本进程不再使用 cosClient 实例之后,关闭即可
cosClient.shutdown();

参数说明

参数名称
参数描述
类型
selectRequest
请求
SelectObjectContentRequest
SelectObjectContentRequest 成员说明:
参数名称
设置方法
描述
类型
bucketName
set 方法
Bucket 的命名格式为 BucketName-APPID ,详情请参见 命名规范
String
key
set 方法
指定分块上传到 COS 上的路径,即 对象键。例如对象键为 folder/picture.jpg
String
expression
set 方法
请求表达式
String
expressionType
set 方法
请求表达式类型
String
inputSerialization
set 方法
描述待检索对象的格式
InputSerialization
outputSerialization
set 方法
描述检索结果的输出格式
OutputSerialization

返回结果说明

成功:返回 InputStream。
失败:发生错误(如身份认证失败),抛出异常 CosClientException 或者 CosServiceException。详情请参见 异常处理