Tous les produits
Search
Centre de documentation

Object Storage Service:Exemple Java : charger des objets vers OSS avec un en-tête signé

Dernière mise à jour :Sep 24, 2026

Présentation

Le kit de développement logiciel (SDK) d'Object Storage Service (OSS) fournit des méthodes pour signer, charger et télécharger des objets. Toutefois, dans certains cas, vous devrez peut-être utiliser une API pour charger et télécharger des objets à l'aide d'une signature. Cette rubrique présente un exemple Java montrant comment réaliser cette opération avec l'opération PutObject.

Remarque

Nous vous recommandons d'utiliser le SDK OSS fourni chaque fois que possible. Cette rubrique propose uniquement un exemple d'implémentation de la signature pour les chargements. Adaptez le code selon vos besoins.

Détails

Le code Java suivant montre comment utiliser l'opération PutObject.

Remarque

JDK 1.8 est requis.

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= "your-bucket-name";
 String accessKeyId= "your-access-key-id";
 String secretAccessKey= "your-access-key-secret";
 String resourcePath = "/xx/panda/102283/111.txt";
 String resourcePath1 = "panda/102283/111.txt";
String VERB = "PUT";
 String url = "https://"+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 {
// Add the request content.
connection= (HttpURLConnection) url1.openConnection();
// Set HTTP connection properties.
connection.setDoOutput(true); // Set this to true because data is in the HTTP body. The default value is false.
connection.setRequestMethod("PUT"); // Submit GET, POST, DELETE, or PUT requests as needed.
//connection.setUseCaches(false); // Configure the cache. Note that the cache cannot be used for POST requests.
// connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Date", date);  // Set the server URL and domain name, for example, ***.**.***.***.
connection.setRequestProperty("Authorization", Authorization); // Set the request format to JSON. You can also set it to XML.
//connection.setRequestProperty("Content-Length", obj.toString().getBytes().length + ""); // Set the length of the file request.

connection.setReadTimeout(10000); // Set the read timeout period.          
connection.setConnectTimeout(10000); // Set the connection timeout period.           
connection.connect();            
OutputStream out = connection.getOutputStream(); // Write data to the object output stream. The data is stored in the memory buffer.          
out.write(new String("test data").getBytes());            //out.write(new String("test data").getBytes()); // Flush the object output stream to write all bytes to the underlying stream.       
out.flush();     
// Close the stream object. No more data can be written to the object output stream. The data written earlier is stored in the memory buffer.          
out.close();           
// Read the response.           
if (connection.getResponseCode()==200)      {
// Obtain an input stream from the server.
InputStreamReader inputStream =new InputStreamReader(connection.getInputStream()); // Call the getInputStream() function of the HttpURLConnection object to send the complete HTTP request message encapsulated in the memory buffer to the server.
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()); 
}    
// Disconnect.           
connection.disconnect();
System.out.println("OK  "+url1);
} catch (IOException e) { 
e.printStackTrace();     
}   
}
}

Références

Ajout d'une signature à l'en-tête

S'applique à

  • Object Storage Service (OSS)