全部產品
Search
文件中心

Object Storage Service:Object Storage Service使用Java實現簽名Header上傳的樣本

更新時間:Dec 31, 2025

概述

Object Storage Service SDK提供了整合簽名、上傳和下載的SDK,但實際使用中,有時需要使用API的方式實現在簽名的情況下進行上傳和下載,本文以PutObject介面為例,提供了Java語言實現的樣本。

說明

建議優先使用OSS提供SDK,本文提供的只是簽名實現上傳樣本,實際使用中需要結合業務進行代碼改動。

詳細資料

Java使用PutObject介面實現範例程式碼如下。

說明

JDK版本為1.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 = VERB + "\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 = "PUT";
 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();     
}   
}
}

相關文檔

在Header中包含簽名

適用於

  • Object Storage Service