Ali cloud OSS Api version (do not use sdk) Tools

 

This article OSS tool to achieve a simple upload and download, a utility class to get, not integrated oss ​​sdk

 Ali cloud official documents Address: https://helpcdn.aliyun.com/document_detail/31947.html

Tools Code

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
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* Classes in java.util. ;
 
public  class OssWebApi { 

    Private  static  Final String ossBucket = "xxx" ;
     Private  static  Final String accessKeyId = "xxx" ;
     Private  static  Final String secretAccessKey = "xxx" ; 

   // can make changes according to their own products oss The domain
Private static Final String Endpoint = "oss-cn-shanghai.aliyuncs.com/" ; Private Final static String CHARSET_UTF8 = "utf8" ; Private Final static String the ALGORITHM = "HmacSHA1" ; //OSS读取 public static String getOssObj(String key) throws IOException { String signResourcePath = "/"+ossBucket+key; String url = "http://"+ossBucket+"."+endpoint; String date = getGMTDate(); String Signature = (hmacSha1(buildGetSignData(date,signResourcePath),secretAccessKey)); String Authorization = "OSS " + accessKeyId + ":" + Signature; Map<String,String> head = new HashMap<String,String>(); head.put("Date",date); head.put("Authorization",Authorization); return get(url + key, head); } //OSS上传 public static String putOssObj(String key,String content) throws IOException { String date = getGMTDate(); String signResourcePath = "/"+ossBucket+key; String connectUrl = "http://"+ossBucket+"."+endpoint; String Signature = (hmacSha1(buildPutSignData(date,signResourcePath),secretAccessKey)); String Authorization = "OSS " + accessKeyId + ":" + Signature; URL putUrl = new URL(connectUrl + key); HttpURLConnection connection; StringBuffer sbuffer = null; try { //添加 请求内容 connection= (HttpURLConnection) putUrl.openConnection(); //设置http连接属性 connection.setDoOutput(true); connection.setRequestMethod("PUT"); //设置请求头 connection.setRequestProperty("Date", date); connection.setRequestProperty ( "the Authorization" , the Authorization); connection.setReadTimeout ( 10000); // set the read timeout connection.setConnectTimeout (10000); // Set the connection timeout connection.connect (); the OutputStream OUT = connection.getOutputStream (); out.write ( new new String (Content) .getBytes ()); out.flush (); the out.close (); // read response IF (connection.getResponseCode () == 200 is ) { // from server gets an input stream InputStreamReader inputStream =new InputStreamReader(connection.getInputStream()); 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{ //连接失败 return null; } //断开连接 connection.disconnect(); } catch (IOException e) { e.printStackTrace(); } return key; } public static String get(String url,Map<String,String> head)throws IOException { HttpClient client = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); for(String key : head.keySet()){ httpGet.setHeader(key,head.get(key)); } HttpResponse response = client.execute(httpGet); response.getEntity().getContent(); HttpEntity entity = response.getEntity(); return EntityUtils.toString(entity, "utf-8"); } public static String hmacSha1(String data, String key) { try { Mac mac = Mac.getInstance("HmacSHA1"); 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 buildGetSignData(String Date,String CanonicalizedResource){ return "GET" + "\n"+ "\n"+ "\n" + Date + "\n" + CanonicalizedResource; } public static String buildPutSignData(String Date,String CanonicalizedResource){ return "PUT" + "\n"+ "\n"+ "\n" + Date + "\n" + CanonicalizedResource; } 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")); return sdf.format(cd.getTime()); } }

 

Example calls

public class Test {
    public static void main(String[] args) throws Exception{//api请求示例
        String getResult = OssWebApi.getOssObj("/test/1.txt");
        System.out.println(getResult);

        String putResult = OssWebApi.putOssObj("/test/aaaa.txt", "this is test content");
        System.out.println(putResult);
    }
}

 

Guess you like

Origin www.cnblogs.com/vicF/p/11510786.html