package com.bcxin.survey.service.obs; import com.bcxin.survey.utils.ConfigUtil; import com.obs.services.ObsClient; import com.obs.services.ObsConfiguration; import com.obs.services.exception.ObsException; import com.obs.services.model.PutObjectResult; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; public class OBSUtil { public static String OSS_BUCKETNAME_TEST = "bcxin-pss-test"; public static String OSS_BUCKETNAME_PROD = "bcxin-pss-prod"; private static final String END_POINT = "https://obs.cn-north-1.myhuaweicloud.com"; private static final String AK = "YYSIHHGD8VTNTQVA2NCB"; private static final String SK = "fd3My9hE8N7Byl4SJ8Mx0kKcn7gvaZoh506WGC0y"; private static ObsClient obsClient; private String bucketName; public OBSUtil() { String profile = ConfigUtil.envi(); /*if ("pro".equals(profile)) { bucketName = OSS_BUCKETNAME_PROD; } else { bucketName = OSS_BUCKETNAME_TEST; }*/ bucketName = OSS_BUCKETNAME_PROD; } public String put(String folder, String ossKey, InputStream inputStream) throws IOException { /* 初始化obs客户端*/ ObsConfiguration config = new ObsConfiguration(); config.setSocketTimeout(30000); config.setConnectionTimeout(10000); config.setEndPoint(END_POINT); try { obsClient = new ObsClient(AK, SK, config); /* 创建文件夹*/ try { obsClient.getObject(bucketName, folder, null); } catch (ObsException e) { /* 文件夹不存在,重新创建文件夹*/ if ("NoSuchKey".equals(e.getErrorCode())) { obsClient.putObject(bucketName, folder, new ByteArrayInputStream(new byte[0])); } } PutObjectResult response = obsClient.putObject(bucketName, ossKey, inputStream); return response.getObjectUrl(); } catch (ObsException e) { System.out.println("Response Code: " + e.getResponseCode()); System.out.println("Error Message: " + e.getErrorMessage()); System.out.println("Error Code: " + e.getErrorCode()); System.out.println("Request ID: " + e.getErrorRequestId()); System.out.println("Host ID: " + e.getErrorHostId()); } finally { if (obsClient != null) { try { obsClient.close(); } catch (IOException e) { } } } return null; } }