2013-05-14 135 views
1

我想獲取Amazon S3中的存儲桶中的對象和文件夾列表,但我不能,我不應該使用Amazon S3 SDK。Amazon S3存儲桶子對象REST和不帶SDK的Java

重要的是不要使用SDK,只有Rest和Java應該發送請求然後接收響應。 我有這樣的方法:

public String BucketSubList(String strPath) throws Exception { 

    String answer = null; 

    // S3 timestamp pattern. 
    String fmt = "EEE, dd MMM yyyy HH:mm:ss "; 
    SimpleDateFormat df = new SimpleDateFormat(fmt, Locale.US); 
    df.setTimeZone(TimeZone.getTimeZone("GMT")); 

    // Data needed for signature 
    String method = "GET"; 
    String contentMD5 = ""; 
    String contentType = ""; 
    String date = df.format(new Date()) + "GMT"; 
    String bucket = "/" + strPath + "/"; 

    // Generate signature 
    StringBuffer buf = new StringBuffer(); 
    buf.append(method).append("\n"); 
    buf.append(contentMD5).append("\n"); 
    buf.append(contentType).append("\n"); 
    buf.append(date).append("\n"); 
    buf.append(bucket); 
    // try { 
    String signature = sign(buf.toString()); 

    // Connection to s3.amazonaws.com 
    URL url = new URL("http", "s3.amazonaws.com", 80, bucket); 

    HttpURLConnection httpConn = null; 
    httpConn = (HttpURLConnection) url.openConnection(); 
    httpConn.setDoInput(true); 
    httpConn.setDoOutput(true); 
    httpConn.setUseCaches(false); 
    httpConn.setDefaultUseCaches(false); 
    httpConn.setAllowUserInteraction(true); 
    httpConn.setRequestMethod(method); 
    httpConn.setRequestProperty("Date", date); 
    // httpConn.setRequestProperty("Content-Type", "text/plain"); 

    String AWSAuth = "AWS " + keyId + ":" + signature; 
    httpConn.setRequestProperty("Authorization", AWSAuth); 

    // Send the HTTP PUT request. 
    int statusCode = httpConn.getResponseCode(); 
    System.out.println(statusCode); 
    if ((statusCode/100) != 2) { 
     // Deal with S3 error stream. 
     InputStream in = httpConn.getErrorStream(); 
     String errorStr = getS3ErrorCode(in); 
     System.out.println("Error: " + errorStr); 
    } else { 
     answer = ""; 
     // System.out.println("Bucket listed successfully"); 
     InputStream inst = httpConn.getInputStream(); 
     BufferedReader in = new BufferedReader(new InputStreamReader(inst)); 
     String decodedString; 
     while ((decodedString = in.readLine()) != null) { 
      answer += decodedString; 
      System.out.println(answer); 
     } 
     in.close(); 
    } 

    return answer; 
} 
+1

問題是什麼? – 2013-05-14 10:43:26

+0

這聽起來很像家庭作業。 – 2013-05-14 16:26:36

回答

1

不知道你的問題是什麼,我只可以給你的鏈接AWS S3 Rest API

This method做你想做的。

我希望這可以幫助你。

否則,請給我們一些關於您的問題的更多信息。

相關問題