|
| 1 | +import com.qiniu.common.QiniuException; |
| 2 | +import com.qiniu.http.Client; |
| 3 | +import com.qiniu.http.Response; |
| 4 | +import com.qiniu.util.Auth; |
| 5 | +import com.qiniu.util.StringMap; |
| 6 | +import com.qiniu.util.UrlSafeBase64; |
| 7 | + |
| 8 | +import java.util.HashMap; |
| 9 | +import java.util.Iterator; |
| 10 | +import java.util.Map; |
| 11 | + |
| 12 | +public class QNMetaDemo { |
| 13 | + //设置好账号的ACCESS_KEY和SECRET_KEY |
| 14 | + private static final String ACCESS_KEY = "填写你们自己的AK"; |
| 15 | + private static final String SECRET_KEY = "填写你们自己的SK"; |
| 16 | + private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY); |
| 17 | + |
| 18 | + private Client client = new Client(); |
| 19 | + private String bucketName; |
| 20 | + private String rsHost; |
| 21 | + |
| 22 | + { |
| 23 | + bucketName = "填写你们自己的存储空间"; |
| 24 | + //设置存储区域rs域名,华东z0 华北z1 华南z2 |
| 25 | + rsHost = "rs-z2.qiniu.com"; |
| 26 | + } |
| 27 | + |
| 28 | + public static void main(String[] args) throws Exception { |
| 29 | + QNMetaDemo qnMetaDemo = new QNMetaDemo(); |
| 30 | + //需要设置自定义meta的空间文件名称 |
| 31 | + String key = "1.mp4"; |
| 32 | + //设置自定义的meta头部,注意,每次调用该接口,是直接覆盖meta,不是追加meta |
| 33 | + HashMap<String, String> metaKeyVal = new HashMap<>(); |
| 34 | + metaKeyVal.put("eng1", "qiniu"); |
| 35 | + metaKeyVal.put("eng2", "七牛"); |
| 36 | + boolean result = qnMetaDemo.setMeta(qnMetaDemo.bucketName, key, metaKeyVal); |
| 37 | + if(result){ |
| 38 | + System.out.println("done"); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * @param bucket 存储空间名称 |
| 44 | + * @param key 存储空间的文件名称 |
| 45 | + * @param headers 自定义的请求头 key - val map |
| 46 | + * @return true or false |
| 47 | + * @throws QiniuException |
| 48 | + */ |
| 49 | + public boolean setMeta(String bucket, String key, Map<String, String> headers) throws QiniuException { |
| 50 | + String resource = UrlSafeBase64.encodeToString(bucket.concat(":").concat(key)); |
| 51 | + String path = String.format("/setmeta/%s", resource); |
| 52 | + String k; |
| 53 | + String encodedMetaValue; |
| 54 | + for(Iterator var6 = headers.keySet().iterator(); var6.hasNext(); path = String.format("%s/x-qn-meta-%s/%s", path, k, encodedMetaValue)) { |
| 55 | + k = (String)var6.next(); |
| 56 | + encodedMetaValue = UrlSafeBase64.encodeToString((String)headers.get(k)); |
| 57 | + } |
| 58 | + //接口请求地址 |
| 59 | + String url = String.format("https://%s%s", rsHost, path); |
| 60 | + System.out.println(url); |
| 61 | + Response res = this.post(url); |
| 62 | + if (res.statusCode != 200) { |
| 63 | + return false; |
| 64 | + } else { |
| 65 | + return true; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + private Response post(String url) throws QiniuException { |
| 70 | + StringMap headers = this.auth.authorization(url); |
| 71 | + return this.client.post(url, null, headers, "application/x-www-form-urlencoded"); |
| 72 | + } |
| 73 | +} |
0 commit comments