2013-08-30 200 views
0

我試圖從android應用上傳.txt文件到Amazon S3存儲桶。從Android上傳到Amazon S3

按照下面的下面tutorial是我的代碼:

 // 
    public class PutOrderFilesTask extends AsyncTask<String, Long, Integer> { 

    public MainActivity parentActivity; 

    public PutOrderFilesTask(MainActivity receivedParentActivity) { 
     this.parentActivity = receivedParentActivity; 
    } 

    @Override 
    protected Integer doInBackground(String... arg0) { 
     Map params = new HashMap(); 
     Uri uri = Uri.parse((parentActivity.getFilesDir()).toString()); 

     params.put("AWSAccessKeyId", "myAWSAccessKeyId"); 
     params.put("Content-Type", "text/xml"); 
     params.put("policy", "some-policy-defined-by-yourself"); 
     params.put("Filename", getManfcAndModelNumb() + ".txt"); 
     params.put("key", getManfcAndModelNumb() + ".txt"); 
     params.put("acl", "private"); 
     params.put("signature", "myApp"); 
     params.put("success_action_status", "201"); 

     Log.e("-o-o--o-o--o-o--o-o--o-o--o-o--o-o--o-o-", "-o-o--o-o--o-o--o-o--o-o--o-o--o-o--o-o--o-o--o-o--o-o--o-o--o-o--o-o--o-o--o-o--o-o"); 

     Log.e(TAG + " - doInBackground(String... arg0)", "Params have been set up"); 

     try { 
      HttpRequest httpRequest = new HttpRequest(); 

      Log.e(TAG + " - doInBackground(String... arg0)", "httpRequest object has been created."); 

      httpRequest.postSocket("uri", 
            params, 
            parentActivity.getContentResolver().openInputStream(uri), 
            this, 
            10, 
            70, 
            getManfcAndModelNumb() + ".txt", 
            getManfcAndModelNumb() + ".txt"); 

      Log.e(TAG + " - doInBackground(String... arg0)", "httpRequest.postSocket() has been called."); 

       /*HttpRequest.postSocket("your-bucket-name.s3.amazonaws.com", params, 
     context.getContentResolver().openInputStream(uri) 
     fileSize, this, 10, 70, "photo.jpg", "image/jpeg");*/ 
     } catch (Exception e) { 
      Log.e(TAG + " - doInBackground(String... arg0)", "httpRequest.postSocket() has NOT been called."); 

      return -1; 
     } 

     return 1; 
    } 

    } 

    // 
    public class HttpRequest { 

    private final String boundary = "-----------------------******"; 
    private final String newLine = "\r\n"; 
    private final int maxBufferSize = 4096; 

    private final String header = 
     "POST/HTTP/1.1\n" + 
     "Host: %s\n" + 
     "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.10) Gecko/20071115 Firefox/2.0.0.10\n" + 
     "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\n" + 
     "Accept-Language: en-us,en;q=0.5\n" + 
     "Accept-Encoding: gzip,deflate\n" + 
     "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\n" + 
     "Keep-Alive: 300\n" + 
     "Connection: keep-alive\n" + 
     "Content-Type: multipart/form-data; boundary=" + boundary + "\n" + 
     "Content-Length: %s\n\n"; 

    public void postSocket(String sUrl, 
          Map params, 
          InputStream stream, 
          PutOrderFilesTask task, 
          int startProgress, 
          int endProgress, 
          String fileName, 
          String contentType) { 

     OutputStream writer = null; 
     BufferedReader reader = null; 
     Socket socket = null; 

     Log.e(TAG + " - postSocket()", "vars in post socket have been populated."); 

     try { 
      int bytesAvailable; 
      int bufferSize; 
      int bytesRead; 
      //int totalProgress = endProgress - startProgress; 

      //task.myPublishProgress(new Long(startProgress)); 

      String openingPart = writeContent(params, fileName, contentType); 
      String closingPart = newLine + "--" + boundary + "--" + newLine; 
      long totalLength = openingPart.length() + closingPart.length(); 

      // strip off the leading http:// otherwise the Socket will not work 
      String socketUrl = sUrl; 

      Log.e(TAG + " - postSocket()", "socketUrl is: " + socketUrl); 

      if (socketUrl.startsWith("http://")) { 
       socketUrl = socketUrl.substring("http://".length()); 
      } 

      socket = new Socket(socketUrl, 80); 

      Log.e(TAG + " - postSocket()", "Socket as a string: " + socket.getPort()); 
      Log.e(TAG + " - postSocket()", "Socket port number is: " + socket.getPort()); 
      Log.e(TAG + " - postSocket()", "Connection state of socket is: " + socket.isConnected()); 

      socket.setKeepAlive(true); 

      writer = socket.getOutputStream(); 
      reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

      writer.write(String.format(header, socketUrl, Long.toString(totalLength)).getBytes()); 
      writer.write(openingPart.getBytes()); 

      bytesAvailable = stream.available(); 
      bufferSize = Math.min(bytesAvailable, maxBufferSize); 

      Log.e(TAG + " - postSocket()", "bufferSize is: " + bufferSize); 

      byte[] buffer = new byte[bufferSize]; 
      bytesRead = stream.read(buffer, 0, bufferSize); 
      int readSoFar = bytesRead; 

      //task.myPublishProgress(new Long(startProgress + Math.round(totalProgress * readSoFar/streamLength))); 

      while (bytesRead > 0) { 
       writer.write(buffer, 0, bufferSize); 
       bytesAvailable = stream.available(); 
       bufferSize = Math.min(bytesAvailable, maxBufferSize); 
       bytesRead = stream.read(buffer, 0, bufferSize); 
       readSoFar += bytesRead; 
       //task.myPublishProgress(new Long(startProgress + Math.round(totalProgress * readSoFar/streamLength))); 
      } 

      stream.close(); 
      writer.write(closingPart.getBytes()); 

      //Log.d(Cards.LOG_TAG, closingPart); 

      writer.flush(); 

      // read the response 
      String s = reader.readLine(); 
      // do something with response s 
     } catch (Exception e) { 
      //throw new HttpRequestException(e); 

      Log.e(TAG + " - postSocket()", "Catch bit of the try and catch in postSocket()"); 
     } finally { 
      if (writer != null) { try { writer.close(); writer = null;} catch (Exception ignore) {}} 
      if (reader != null) { try { reader.close(); reader = null;} catch (Exception ignore) {}} 
      if (socket != null) { try {socket.close(); socket = null;} catch (Exception ignore) {}} 
     } 
    } 

    /** 
     * Populate the multipart request parameters into one large stringbuffer which will later allow us to 
     * calculate the content-length header which is mandatotry when putting objects in an S3 
     * bucket 
     * 
     * @param params 
     * @param fileName the name of the file to be uploaded 
     * @param contentType the content type of the file to be uploaded 
     * @return 
     */ 

    private String writeContent(Map params, String fileName, String contentType) { 

     StringBuffer buf = new StringBuffer(); 

     Set keys = params.keySet(); 

     for (Object key : keys) { 
      Object val = params.get(key); 

      buf.append("--") 
       .append(boundary) 
       .append(newLine); 

      buf.append("Content-Disposition: form-data; name=\"") 
       .append(key) 
       .append("\"") 
       .append(newLine) 
       .append(newLine) 
       .append(val) 
       .append(newLine); 
     } 

     buf.append("--") 
      .append(boundary) 
      .append(newLine); 

     buf.append("Content-Disposition: form-data; name=\"file\"; filename=\"") 
      .append(fileName) 
      .append("\"") 
      .append(newLine); 

     buf.append("Content-Type: ") 
      .append(contentType) 
      .append(newLine) 
      .append(newLine); 

     return buf.toString(); 
    } 

    } 

我的問題是我現在遇到的問題時,我需要所有的postSocket方法如上所示。

任何想法,不勝感激。

注意:方法getManfcAndModelNumb()返回一個字符串。

回答

0

你願意考慮一種替代方案:

 class S3 extends AmazonS3Client 
     {final String bucket; 
      S3(String u, String p, String Bucket) 
      {super(new BasicAWSCredentials(u, p)); 
      bucket = Bucket; 
      } 
      boolean put(String k, String v)  
      {try 
      {final ByteArrayInputStream b = new ByteArrayInputStream(v.toString().getBytes()); 
       putObject(bucket, k, b, new ObjectMetadata()); 
       setObjectAcl(bucket, k, CannedAccessControlList.PublicRead); // Has to be here to allow change to reduced redundancy 
       changeObjectStorageClass(bucket, k, StorageClass.ReducedRedundancy); 
       setObjectAcl(bucket, k, CannedAccessControlList.PublicRead); // Has to be repeated because it is now a new object again 
       return true; 
      } 
      catch(Exception e) {log("Cannot put "+bucket+"/"+k+" to S3 because "+e);} 
      return false; 
      } 
     }