概述
OSS的內建上傳和下載下傳提供了SDK可以直接使用,但實際使用中一些使用者受限環境或者裝置限制需要使用api方式來實作上傳和下載下傳,本文以PutObject接口為例,提供了java實作的demo。
注:建議優先使用OSS提供SDK,本文提供的隻是簽名實作上傳demo,實際使用中需要結合業務來進行改動代碼
詳細資訊
PutObject實作demo(測試環境JDK1.8):
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
public class OssSignHeader {
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
private final static String CHARSET_UTF8 = "utf8";
private final static String ALGORITHM = "HmacSHA1";
public static String hmacSha1(String data, String key) {
try {
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
mac.init(keySpec);
byte[] rawHmac;
rawHmac = mac.doFinal(data.getBytes(CHARSET_UTF8));
return new String(Base64.encodeBase64(rawHmac));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String buildSignData(String Date,String VERB,String CanonicalizedResource){
String signData = "PUT" + "\n"+ "\n"+ "\n"
+ Date + "\n"
+ CanonicalizedResource;
return signData;
}
public static String getGMTDate(){
Calendar cd = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String str = sdf.format(cd.getTime());
return str;
}
public static void main(String[] args) throws Exception{
String date = getGMTDate();
String ossBucket= "您的bucket名稱";
String accessKeyId= "您的AccessKey";
String secretAccessKey= "您的AccessSecret";
String resourcePath = "/xx/panda/102283/111.txt";
String resourcePath1 = "panda/102283/111.txt";
String VERB = "GET";
String url = "http://"+ossBucket+".oss-cn-hangzhou.aliyuncs.com/";
String Signature = (hmacSha1(buildSignData(date,VERB,resourcePath),secretAccessKey));
String Authorization = "OSS " + accessKeyId + ":" + Signature;
System.out.println(Authorization);
Map<String,String> head = new HashMap<String,String>();
head.put("Date",date);
head.put("Authorization",Authorization);
URL url1 = new URL(url + resourcePath1);
HttpURLConnection connection ;
StringBuffer sbuffer=null;
try {
//添加 請求内容
connection= (HttpURLConnection) url1.openConnection();
//設定http連接配接屬性
connection.setDoOutput(true);// http正文内,是以需要設為true, 預設情況下是false;
connection.setRequestMethod("PUT"); // 可以根據需要 送出 GET、POST、DELETE、PUT等http提供的功能
//connection.setUseCaches(false);//設定緩存,注意設定請求方法為post不能用緩存
// connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Date", date); //設定請 求的伺服器網址,域名,例如***.**.***.***
connection.setRequestProperty("Authorization", Authorization);//設定 請求格式 json,也可以設定xml格式的
//connection.setRequestProperty("Content-Length", obj.toString().getBytes().length + ""); //設定檔案請求的長度
connection.setReadTimeout(10000);//設定讀取逾時時間
connection.setConnectTimeout(10000);//設定連接配接逾時時間
connection.connect();
OutputStream out = connection.getOutputStream();//向對象輸出流寫出資料,這些資料将存到記憶體緩沖區中
out.write(new String("測試資料").getBytes()); //out.write(new String("測試資料").getBytes()); //重新整理對象輸出流,将任何位元組都寫入潛在的流中
out.flush();
// 關閉流對象,此時,不能再向對象輸出流寫入任何資料,先前寫入的資料存在于記憶體緩沖區中
out.close();
//讀取響應
if (connection.getResponseCode()==200) {
// 從伺服器獲得一個輸入流
InputStreamReader inputStream =new InputStreamReader(connection.getInputStream());//調用HttpURLConnection連接配接對象的getInputStream()函數, 将記憶體緩沖區中封裝好的完整的HTTP請求電文發送到服務端。
BufferedReader reader = new BufferedReader(inputStream);
String lines;
sbuffer= new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sbuffer.append(lines); }
reader.close();
}else{
System.out.println(connection.getResponseCode());
}
//斷開連接配接
connection.disconnect();
System.out.println("OK "+url1);
} catch (IOException e) {
e.printStackTrace();
}
}
}