多吉云文件上传

master
fst1996 2023-10-05 00:22:09 +08:00
parent a1535c5eb8
commit babdcdafb3
3 changed files with 190 additions and 0 deletions

View File

@ -0,0 +1,121 @@
package com.bwie.duojiyun;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.json.JSONObject;
import org.apache.commons.codec.binary.Hex;
/**
* API
*/
public class DogGetApi {
// 普通 API 请使用这个方法
public static JSONObject dogeAPIGet(String apiPath, Map<String, String> params) {
StringBuilder sb = new StringBuilder();
for(Map.Entry<String, String> hm : params.entrySet()){
try {
sb.append(URLEncoder.encode(hm.getKey(), String.valueOf(StandardCharsets.UTF_8))).append('=').append(URLEncoder.encode(hm.getValue(), String.valueOf(StandardCharsets.UTF_8))).append("&");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
String bodyText = sb.toString().replace("&$", "");
try {
return dogeAPIGet(apiPath, bodyText, false);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
// 要求请求内容 Body 是一个 JSON 的 API请使用这个方法
public static JSONObject dogeAPIGet(String apiPath, JSONObject params) {
String bodyText = params.toString();
try {
return dogeAPIGet(apiPath, bodyText, true);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
// 无参数 API
public static JSONObject dogeAPIGet(String apiPath) {
try {
return dogeAPIGet(apiPath, "", true);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
public static JSONObject dogeAPIGet(String apiPath, String paramsText, Boolean jsonMode) throws IOException{
// 这里返回值类型是 JSONObject你也可以根据你的具体情况使用不同的 JSON 库并修改最下方 JSON 处理代码
// 这里替换为你的多吉云永久 AccessKey 和 SecretKey可在用户中心 - 密钥管理中查看
// 请勿在客户端暴露 AccessKey 和 SecretKey那样恶意用户将获得账号完全控制权
String accessKey = "kjd189189u981kj";
String secretKey = "ada91871ns1jc9711jkn981d";
String signStr = apiPath + "\n" + paramsText;
String sign = "";
try {
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"));
sign = new String(new Hex().encode(mac.doFinal(signStr.getBytes())), StandardCharsets.UTF_8); // 这里 Hex 来自 org.apache.commons.codec.binary.Hex
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} catch (InvalidKeyException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
String authorization = "TOKEN " + accessKey + ':' + sign;
URL u = new URL("https://api.dogecloud.com" + apiPath);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty( "Content-Type", jsonMode ? "application/json" : "application/x-www-form-urlencoded");
conn.setRequestProperty( "Authorization", authorization);
conn.setRequestProperty( "Content-Length", String.valueOf(paramsText.length()));
OutputStream os = conn.getOutputStream();
os.write(paramsText.getBytes());
os.flush();
os.close();
StringBuilder retJSON = new StringBuilder();
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
String readLine = "";
try (BufferedReader responseReader=new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
while((readLine=responseReader.readLine())!=null){
retJSON.append(readLine).append("\n");
}
responseReader.close();
}
JSONObject ret = new JSONObject(retJSON.toString());
if (ret.getInt("code") != 200) {
System.err.println("{\"error\":\"API 返回错误:" + ret.getString("msg") + "\"}");
} else {
JSONObject output = new JSONObject();
JSONObject data = ret.getJSONObject("data");
return data;
}
} else {
System.err.println("{\"error\":\"网络错误:" + conn.getResponseCode() + "\"}");
}
return null;
}
}

View File

@ -0,0 +1,20 @@
package com.bwie.duojiyun;
import org.json.JSONObject;
import static com.bwie.duojiyun.DogGetApi.dogeAPIGet;
public class DuoJiYunUtil {
//用来调用多吉云API获取秘钥
public static JSONObject getCredentials() {
JSONObject body = new JSONObject();
body.put("channel", "OSS_FULL");
body.append("scopes", "*"); // 要操作的存储空间名称,注意不是 s3Bucket 值,也可以设置为 *
JSONObject data = dogeAPIGet("/auth/tmp_token.json", body);
JSONObject credentials = data.getJSONObject("Credentials");
return credentials;
}
}

View File

@ -0,0 +1,49 @@
package com.bwie.duojiyun;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicSessionCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import static com.bwie.duojiyun.DogGetApi.dogeAPIGet;
public class S3 {
public static AmazonS3 initS3(JSONObject credentials){
BasicSessionCredentials awsCredentials = new BasicSessionCredentials(credentials.getString("accessKeyId"), credentials.getString("secretAccessKey"), credentials.getString("sessionToken"));
AmazonS3 s3 = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(
"https://cos.ap-shanghai.myqcloud.com", // 修改为多吉云控制台存储空间 SDK 参数中的 s3Endpoint
"automatic"))
.build();
return s3;
}
public static void main(String[] args) throws Exception {
JSONObject data = dogeAPIGet("/oss/bucket/list.json");
JSONArray buckets = data.getJSONArray("buckets");
for (int i = 0 ; i < buckets.length(); i++) {
System.out.println(buckets.getJSONObject(i).toString());
}
JSONObject credentials = DuoJiYunUtil.getCredentials();
AmazonS3 s3 = initS3(credentials);
PutObjectResult putObjectResult = s3.putObject("s-sh-6719-fst-198781691", "666.png", new File("D:\\fst\\111\\118981998299818921.png"));
String string = putObjectResult.toString();
System.out.println(string);
}
}