阿里雲OSS Api版本(不使用sdk)工具類


 

本文工具實現了OSS簡單的上傳和下載功能,一個工具類搞定,不用集成oss sdk

 阿里雲官方文檔地址:https://helpcdn.aliyun.com/document_detail/31947.html

工具類代碼

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 java.util.*;

public class OssWebApi {

    private static final String ossBucket= "xxx";
    private static final String accessKeyId= "xxx";
    private static final String secretAccessKey= "xxx";

   //可根據自己的oss產品自行更改域名
private static final String endpoint= "oss-cn-shanghai.aliyuncs.com/"; private final static String CHARSET_UTF8 = "utf8"; private final static String 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("Authorization", Authorization); connection.setReadTimeout(10000);//設置讀取超時時間 connection.setConnectTimeout(10000);//設置連接超時時間 connection.connect(); OutputStream out = connection.getOutputStream(); out.write(new String(content).getBytes()); out.flush(); out.close(); //讀取響應 if (connection.getResponseCode()==200) { // 從服務器獲得一個輸入流 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()); } }

 

調用示例

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);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM