Java example: upload objects to OSS with a signed header
Updated at:
Overview
The Object Storage Service (OSS) software development kit (SDK) provides methods to sign, upload, and download objects. However, in some cases, you may need to use an API to upload and download objects using a signature. This topic provides a Java example of how to perform this task using the PutObject operation.
Note
We recommend that you use the provided OSS SDK when possible. This topic provides only an example of how to implement signing for uploads. You must modify the code as needed.
Details
The following Java code shows how to use the PutObject operation.
Note
JDK 1.8 is required.
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();
}
}
}
References
Adding a signature to the header
Applies to
-
Object Storage Service (OSS)
Is this page helpful?