java集成华为云obs上传下载实战

说明

最近项目上需要开发一个服务去和华为云OBS集成获取一些业务上的文件,此处记录一下简单的java集成obs的入门,希望对大家快速入门有所帮助:)

实现效果

  • 上传对象
    java集成华为云obs上传下载实战_第1张图片
  • 下载到本地
    java集成华为云obs上传下载实战_第2张图片

操作步骤

1.开通obs

上华为云官网,注册账号后购买,支付后进入控制台。

2.获取ak/sk等信息

参考:
https://support.huaweicloud.com/eihealth_faq/eihealth_27_0007.html
java集成华为云obs上传下载实战_第3张图片

3.获取官方java demo

https://github.com/huaweicloud/huaweicloud-sdk-java-obs/blob/master/app/src/test/java/samples_java
我这里拿的是:DownloadSample.java

/**
 * This sample demonstrates how to download an object 
 * from OBS in different ways using the OBS SDK for Java.
 */
public class DownloadSample
{
    private static final String endPoint = "https://obs.cn-east-3.myhuaweicloud.com";
    
    private static final String ak = "替换";
    
    private static final String sk = "替换";
    
    private static ObsClient obsClient;
    
    private static String bucketName = "blogstore";
    
    private static String objectKey = "stringdemo";
    
    private static String localFilePath = "d:/temp/" + objectKey;
    
    public static void main(String[] args)
        throws IOException
    {
        ObsConfiguration config = new ObsConfiguration();
        config.setSocketTimeout(30000);
        config.setConnectionTimeout(10000);
        config.setEndPoint(endPoint);
        try
        {
            /*
             * Constructs a obs client instance with your account for accessing OBS
             */
            obsClient = new ObsClient(ak, sk, config);
            
            /*
             * Create bucket 
             */
            System.out.println("Create a new bucket for demo\n");
            //obsClient.createBucket(bucketName);
            
            /*
             * Upload an object to your bucket
             */
            System.out.println("Uploading a new object to OBS from a file\n");
            obsClient.putObject(bucketName, objectKey, createSampleFile());
            
            System.out.println("Downloading an object\n");
            
            /*
             * Download the object as an inputstream and display it directly 
             */
            simpleDownload();
            
            File localFile = new File(localFilePath);
            if (!localFile.getParentFile().exists())
            {
                localFile.getParentFile().mkdirs();
            }
            
            System.out.println("Downloading an object to file:" + localFilePath + "\n");
            /*
             * Download the object to a file
             */
            downloadToLocalFile();
            
            System.out.println("Deleting object  " + objectKey + "\n");
            //obsClient.deleteObject(bucketName, objectKey, null);
            
        }
        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
                {
                    /*
                     * Close obs client 
                     */
                    obsClient.close();
                }
                catch (IOException e)
                {
                }
            }
        }
    }
    
    private static void downloadToLocalFile()
        throws ObsException, IOException
    {
        ObsObject obsObject = obsClient.getObject(bucketName, objectKey, null);
        ReadableByteChannel rchannel = Channels.newChannel(obsObject.getObjectContent());
        
        ByteBuffer buffer = ByteBuffer.allocate(4096);
        WritableByteChannel wchannel = Channels.newChannel(new FileOutputStream(new File(localFilePath)));
        
        while (rchannel.read(buffer) != -1)
        {
            buffer.flip();
            wchannel.write(buffer);
            buffer.clear();
        }
        rchannel.close();
        wchannel.close();
    }
    
    private static void simpleDownload()
        throws ObsException, IOException
    {
        ObsObject obsObject = obsClient.getObject(bucketName, objectKey, null);
        displayTextInputStream(obsObject.getObjectContent());
    }
    
    private static void displayTextInputStream(InputStream input)
        throws IOException
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        while (true)
        {
            String line = reader.readLine();
            if (line == null)
                break;
            
            System.out.println("\t" + line);
        }
        System.out.println();
        
        reader.close();
    }
    
    private static File createSampleFile()
        throws IOException
    {
        File file = File.createTempFile("obs-java-sdk-", ".txt");
        file.deleteOnExit();
        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
        writer.write("abcdefghijklmnopqrstuvwxyz\n");
        writer.write("0123456789011234567890\n");
        writer.close();
        
        return file;
    }
    
}

4.运行demo

创建工程添加pom依赖:

<dependency>
	    <groupId>com.huaweicloudgroupId>
	    <artifactId>esdk-obs-java-bundleartifactId>
	    <version>[3.21.8,)version>
	dependency>

修改样例代码中的配置项信息,运行。

常用链接

1.获取地区endpoint

https://developer.huaweicloud.com/endpoint

2.spingboot集成obs

https://www.dandelioncloud.cn/article/details/1389618552004751362

常见错误

1.endpoint地区不对

Response Code: 400

Error Message: The location constraint is incompatible for the region specific endpoint this request was sent to.

你可能感兴趣的:(Java项目实战,java,开发语言,华为obs)