华为云对象存储OBS通过header鉴权访问obsS(Java SDK)_云淘科技

代码示例:上传对象

 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
import com.obs.services.internal.Constants;
import com.obs.services.internal.utils.AbstractAuthentication;
import com.obs.services.model.AuthTypeEnum;
import shade.okhttp3.Call;
import shade.okhttp3.MediaType;
import shade.okhttp3.OkHttpClient;
import shade.okhttp3.Request;
import shade.okhttp3.RequestBody;
import shade.okhttp3.Response;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
public class PutObjectTemporaryHeaderToObs {
    // 您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。如果使用硬编码可能会存在泄露风险。
    // 您可以登录访问管理控制台获取访问密钥AK/SK
    private static String ak = System.getenv("ACCESS_KEY_ID");
    private static String sk = System.getenv("SECRET_ACCESS_KEY_ID");
    // 【可选】如果使用临时AK/SK和SecurityToken访问OBS,同样建议您尽量避免使用硬编码,以降低信息泄露风险。
    // 您可以通过环境变量获取访问密钥AK/SK/SecurityToken,也可以使用其他外部引入方式传入。
    private static String securityToken = System.getenv("SECURITY_TOKEN");
    // 您可以通过环境变量获取endPoint,也可以使用其他外部引入方式传入。
    //private static String endPoint = System.getenv("ENDPOINT");
    // endpoint填写桶所在的endpoint, 此处以华北-北京四为例,其他地区请按实际情况填写。
    private static String endPoint = "obs.cn-north-4.myhuaweicloud.com";
    private static String bucketName = "examplebucket";
    private static String objectName = "objectName";
    private static String contentType = "application/xml";
    private static Map headers = new HashMap();
    public static void main(String[] args) throws Exception {
        headers.put("Content-Type", contentType);
        DateFormat dateFormat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date now = new Date(System.currentTimeMillis());
        headers.put("x-obs-date", dateFormat.format(now));
        sign("PUT", "/" + bucketName + "/" + objectName);
        Request.Builder builder = new Request.Builder();
        for (Map.Entry entry : headers.entrySet()) {
            builder.header(entry.getKey(), entry.getValue());
        }
        String url = "https://" + bucketName + "." + endPoint + "/" + objectName;
        //使用PUT请求上传对象
        Request httpRequest = builder.url(url).put(RequestBody.create(MediaType.parse(contentType), "Hello OBS".getBytes("UTF-8"))).build();
        OkHttpClient httpClient = new OkHttpClient.Builder().followRedirects(false).retryOnConnectionFailure(false)
                .cache(null).build();
        Call c = httpClient.newCall(httpRequest);
        Response res = c.execute();
        System.out.println("	Status:" + res.code());
        if (res.body() != null) {
            System.out.println("	Content:" + res.body().string() + "
");
        }
        res.close();
    }
    public static void sign(String method, String url) throws Exception {
        AbstractAuthentication authentication =
                Constants.AUTHTICATION_MAP.get(AuthTypeEnum.OBS);
        String stringToSign = authentication.makeServiceCanonicalString(method, url, headers, null, Constants.ALLOWED_RESOURCE_PARAMTER_NAMES);
        System.out.println("stringToSign: " + stringToSign);
        String auth = "OBS " + ak + ":" + AbstractAuthentication.calculateSignature(stringToSign, sk);
        headers.put("Authorization", auth);
    }
}

代码示例:初始化分段上传任务

 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
import com.obs.services.internal.Constants;
import com.obs.services.internal.utils.AbstractAuthentication;
import com.obs.services.model.AuthTypeEnum;
import com.obs.services.model.SpecialParamEnum;
import shade.okhttp3.Call;
import shade.okhttp3.MediaType;
import shade.okhttp3.OkHttpClient;
import shade.okhttp3.Request;
import shade.okhttp3.RequestBody;
import shade.okhttp3.Response;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
public class initiateMultipartUpload {
    // 您可以通过环境变量获取endPoint,也可以使用其他外部引入方式传入。
    //private static String endPoint = System.getenv("ENDPOINT");
    // endpoint填写桶所在的endpoint, 此处以华北-北京四为例,其他地区请按实际情况填写。
    private static String endPoint = "obs.cn-north-4.myhuaweicloud.com";
    private static String ak = System.getenv("ACCESS_KEY_ID");
    private static String sk = System.getenv("SECRET_ACCESS_KEY_ID");
    private static String bucketName = "examplebucket";
    private static String objectName = "objectName";
    private static String contentType = "application/xml";
    private static Map headers = new HashMap();
    public static void main(String[] args) throws Exception {
        DateFormat dateFormat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date now = new Date(System.currentTimeMillis());
        headers.put("x-obs-date", dateFormat.format(now));
        sign("POST", "/" + bucketName + "/" + objectName + "?uploads");
        Request.Builder builder = new Request.Builder();
        for (Map.Entry entry : headers.entrySet()) {
            builder.header(entry.getKey(), entry.getValue());
        }
        String url = "https://" + bucketName + "." + endPoint + "/" + objectName + "?uploads";
        //使用POST请求初始化分段上传任务
        Request httpRequest = builder.url(url).post(RequestBody.create(null, "")).build();
        OkHttpClient httpClient = new OkHttpClient.Builder().followRedirects(false).retryOnConnectionFailure(false)
                .cache(null).build();
        Call c = httpClient.newCall(httpRequest);
        Response res = c.execute();
        System.out.println("	Status:" + res.code());
        if (res.body() != null) {
            System.out.println("	Content:" + res.body().string() + "
");
        }
        res.close();
    }
    public static void sign(String method, String url) throws Exception {
        AbstractAuthentication authentication =
                Constants.AUTHTICATION_MAP.get(AuthTypeEnum.OBS);
        String stringToSign = authentication.makeServiceCanonicalString(method, url, headers, null, Constants.ALLOWED_RESOURCE_PARAMTER_NAMES);
        System.out.println("stringToSign: " + stringToSign);
        String auth = "OBS " + ak + ":" + AbstractAuthentication.calculateSignature(stringToSign, sk);
        headers.put("Authorization", auth);
    }
}

代码示例:上传段

 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
import com.obs.services.internal.Constants;
import com.obs.services.internal.utils.AbstractAuthentication;
import com.obs.services.model.AuthTypeEnum;
import shade.okhttp3.Call;
import shade.okhttp3.MediaType;
import shade.okhttp3.OkHttpClient;
import shade.okhttp3.Request;
import shade.okhttp3.RequestBody;
import shade.okhttp3.Response;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
public class UploadPart {
    // 您可以通过环境变量获取endPoint,也可以使用其他外部引入方式传入。
    //private static String endPoint = System.getenv("ENDPOINT");
    // endpoint填写桶所在的endpoint, 此处以华北-北京四为例,其他地区请按实际情况填写。
    private static String endPoint = "obs.cn-north-4.myhuaweicloud.com";
    private static String ak = System.getenv("ACCESS_KEY_ID");
    private static String sk = System.getenv("SECRET_ACCESS_KEY_ID");
    private static String bucketName = "examplebucket";
    private static String objectName = "objectName";
    private static String contentType = "application/xml";
    private static Map headers = new HashMap();
    public static void main(String[] args) throws Exception {
        DateFormat dateFormat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date now = new Date(System.currentTimeMillis());
        headers.put("x-obs-date", dateFormat.format(now));
        sign("PUT", "/" + bucketName + "/" + objectName + "?partNumber=1&uploadId=0000018A0CA7D2144015626C08A6067A");
        Request.Builder builder = new Request.Builder();
        for (Map.Entry entry : headers.entrySet()) {
            builder.header(entry.getKey(), entry.getValue());
        }
        String url = "https://" + bucketName + "." + endPoint + "/" + objectName + "?partNumber=1&uploadId=0000018A0CA7D2144015626C08A6067A";
        //使用PUT请求上传对象
        Request httpRequest = builder.url(url).put(RequestBody.create(null, new byte[6 * 1024 * 1024])).build();
        OkHttpClient httpClient = new OkHttpClient.Builder().followRedirects(false).retryOnConnectionFailure(false)
                .cache(null).build();
        Call c = httpClient.newCall(httpRequest);
        Response res = c.execute();
        System.out.println("	Status:" + res.code());
        if (res.body() != null) {
            System.out.println("	Content:" + res.body().string() + "
");
        }
        res.close();
    }
    public static void sign(String method, String url) throws Exception {
        AbstractAuthentication authentication =
                Constants.AUTHTICATION_MAP.get(AuthTypeEnum.OBS);
        String stringToSign = authentication.makeServiceCanonicalString(method, url, headers, null, Constants.ALLOWED_RESOURCE_PARAMTER_NAMES);
        System.out.println("stringToSign: " + stringToSign);
        String auth = "OBS " + ak + ":" + AbstractAuthentication.calculateSignature(stringToSign, sk);
        headers.put("Authorization", auth);
    }
}

代码示例:合并段

 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
import com.obs.services.internal.Constants;
import com.obs.services.internal.utils.AbstractAuthentication;
import com.obs.services.model.AuthTypeEnum;
import shade.okhttp3.Call;
import shade.okhttp3.MediaType;
import shade.okhttp3.OkHttpClient;
import shade.okhttp3.Request;
import shade.okhttp3.RequestBody;
import shade.okhttp3.Response;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
public class CompeletePart {
    // 您可以通过环境变量获取endPoint,也可以使用其他外部引入方式传入。
    //private static String endPoint = System.getenv("ENDPOINT");
    // endpoint填写桶所在的endpoint, 此处以华北-北京四为例,其他地区请按实际情况填写。
    private static String endPoint = "obs.cn-north-4.myhuaweicloud.com";
    private static String ak = System.getenv("ACCESS_KEY_ID");
    private static String sk = System.getenv("SECRET_ACCESS_KEY_ID");
    private static String bucketName = "examplebucket";
    private static String objectName = "objectName";
    private static String contentType = "application/xml";
    private static Map headers = new HashMap();
    public static void main(String[] args) throws Exception {
        headers.put("Content-Type", contentType);
        DateFormat dateFormat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date now = new Date(System.currentTimeMillis());
        headers.put("x-obs-date", dateFormat.format(now));
        sign("POST", "/" + bucketName + "/" + objectName + "?uploadId=0000018A0CA7D2144015626C08A6067A");
        Request.Builder builder = new Request.Builder();
        for (Map.Entry entry : headers.entrySet()) {
            builder.header(entry.getKey(), entry.getValue());
        }
        String url = "https://" + bucketName + "." + endPoint + "/" + objectName + "?uploadId=0000018A0CA7D2144015626C08A6067A";
        //使用POST请求初始化分段上传任务
        // 以下content为示例代码,需要通过列举已上传段方法的响应结果,拼装以下内容
        String content = "";
        content += "";
        content += "1";
        content += "da6a0d097e307ac52ed9b4ad551801fc";
        content += "";
        content += "";
        Request httpRequest = builder.url(url).post(RequestBody.create(MediaType.parse(contentType), content.getBytes("UTF-8"))).build();
        OkHttpClient httpClient = new OkHttpClient.Builder().followRedirects(false).retryOnConnectionFailure(false)
                .cache(null).build();
        Call c = httpClient.newCall(httpRequest);
        Response res = c.execute();
        System.out.println("	Status:" + res.code());
        if (res.body() != null) {
            System.out.println("	Content:" + res.body().string() + "
");
        }
        res.close();
    }
    public static void sign(String method, String url) throws Exception {
        AbstractAuthentication authentication =
                Constants.AUTHTICATION_MAP.get(AuthTypeEnum.OBS);
        String stringToSign = authentication.makeServiceCanonicalString(method, url, headers, null, Constants.ALLOWED_RESOURCE_PARAMTER_NAMES);
        System.out.println("stringToSign: " + stringToSign);
        String auth = "OBS " + ak + ":" + AbstractAuthentication.calculateSignature(stringToSign, sk);
        headers.put("Authorization", auth);
    }
}

父主题: 临时授权访问(Java SDK)

同意关联代理商云淘科技,购买华为云产品更优惠(QQ 78315851)

内容没看懂? 不太想学习?想快速解决? 有偿解决: 联系专家