18034727885
2026-03-25 588b60be435c60da422c7e67f15bec9ffe97cd51
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package com.jxonlinecar.driver.utils;
 
import android.util.Log;
 
import androidx.annotation.NonNull;
 
import com.jxonlinecar.driver.base.Const;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.PutObjectRequest;
import com.obs.services.model.PutObjectResult;
 
import java.io.File;
import java.util.UUID;
 
/**
 * 上传管理器
 */
public class UploadManager {
    private static final String TAG = "UploadManager";
    // 创建华为云ObsClient实例
    private ObsClient obsClient;
 
    public UploadManager() {
    }
 
    /**
     * 初始化华为云
     */
    public void initHW() {
        obsClient = new ObsClient(Const.accessKeyId, Const.accessKeySecret, Const.end_point);
    }
 
    /**
     * 上传华为云,耗时操作
     *
     * @param file 文件
     */
    public String uploadHWSync(@NonNull File file) {
        if (obsClient == null) {
            Log.d(TAG, "not init");
            return null;
        }
        try {
            // 文件上传
            // localfile 为待上传的本地文件路径,需要指定到具体的文件名
            PutObjectRequest request = new PutObjectRequest();
            request.setBucketName(Const.bucketName);
            String objectKey = UUID.randomUUID().toString();
            request.setObjectKey(objectKey);
            request.setFile(file);
            PutObjectResult putObjectResult = obsClient.putObject(request);
            if (putObjectResult.getStatusCode() == 200) {
                Log.d(TAG, "putObject successfully");
                return putObjectResult.getObjectUrl();
            }
        } catch (ObsException e) {
            Log.d(TAG, "putObject failed");
            // 请求失败,打印http状态码
            Log.d(TAG, "HTTP Code:" + e.getResponseCode());
            // 请求失败,打印服务端错误码
            Log.d(TAG, "Error Code:" + e.getErrorCode());
            // 请求失败,打印详细错误信息
            Log.d(TAG, "Error Message:" + e.getErrorMessage());
            // 请求失败,打印请求id
            Log.d(TAG, "Request ID:" + e.getErrorRequestId());
            Log.d(TAG, "Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            Log.d(TAG, "putObject failed");
            // 其他异常信息打印
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 释放资源
     */
    public void release() {
        if (obsClient != null) {
            try {
                obsClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        obsClient = null;
    }
}