Android上传图片到amzon s3显示java.lang.IllegalStateException:内容已消耗错误

时间:2015-06-17 11:13:14

标签: android amazon-web-services amazon-s3 image-uploading

我通过Android应用程序从图库将图像上传到Amazon S3。

显示java.lang.IllegalStateException:内容已消耗错误

我在下面添加了我的代码,请帮我解决一下。

我是这样的错误

06-17 17:23:22.908: W/System.err(27214): java.lang.IllegalStateException: Content has been consumed
06-17 17:23:22.909: W/System.err(27214):    at org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:84)
06-17 17:23:22.909: W/System.err(27214):    at com.amazonaws.http.AmazonHttpClient.executeHelper(Unknown Source)
06-17 17:23:22.910: W/System.err(27214):    at com.amazonaws.http.AmazonHttpClient.execute(Unknown Source)
06-17 17:23:22.910: W/System.err(27214):    at com.amazonaws.services.s3.AmazonS3Client.invoke(Unknown Source)
06-17 17:23:22.910: W/System.err(27214):    at com.amazonaws.services.s3.AmazonS3Client.uploadPart(Unknown Source)
06-17 17:23:22.911: W/System.err(27214):    at com.readystatesoftware.simpl3r.Uploader.start(Uploader.java:162)
06-17 17:23:22.911: W/System.err(27214):    at com.readystatesoftware.simpl3r.example.UploadService.onHandleIntent(UploadService.java:103)
06-17 17:23:22.911: W/System.err(27214):    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
06-17 17:23:22.911: W/System.err(27214):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-17 17:23:22.912: W/System.err(27214):    at android.os.Looper.loop(Looper.java:153)
06-17 17:23:22.912: W/System.err(27214):    at android.os.HandlerThread.run(HandlerThread.java:60)

UploadService.java

public class UploadService extends IntentService {

    public static final String ARG_FILE_PATH = "file_path";
    public static final String UPLOAD_STATE_CHANGED_ACTION = "com.readystatesoftware.simpl3r.example.UPLOAD_STATE_CHANGED_ACTION";
    public static final String UPLOAD_CANCELLED_ACTION = "com.readystatesoftware.simpl3r.example.UPLOAD_CANCELLED_ACTION";
    public static final String S3KEY_EXTRA = "s3key";
    public static final String PERCENT_EXTRA = "percent";
    public static final String MSG_EXTRA = "msg";

    private static final int NOTIFY_ID_UPLOAD = 1337;

    private AmazonS3Client s3Client;
    private Uploader uploader;

    private NotificationManager nm;

    public UploadService() {
        super("simpl3r-example-upload");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        s3Client = new AmazonS3Client(
                new BasicAWSCredentials(getString(R.string.s3_access_key), getString(R.string.s3_secret)));
        nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        IntentFilter f = new IntentFilter();
        f.addAction(UPLOAD_CANCELLED_ACTION);
        registerReceiver(uploadCancelReceiver, f);
    }   

    @Override
    protected void onHandleIntent(Intent intent) {


        String filePath = intent.getStringExtra(ARG_FILE_PATH);
        File fileToUpload = new File(filePath);
        final String s3ObjectKey = md5(filePath);
        String s3BucketName = getString(R.string.s3_bucket);

        final String msg = "Uploading " + s3ObjectKey + "...";

        // create a new uploader for this file
        uploader = new Uploader(this, s3Client, s3BucketName, s3ObjectKey, fileToUpload);

    /*  File theFile = new File(filePath);
         PutObjectRequest putObjectRequest = new PutObjectRequest(amazonFileUploadLocationOriginal, keyName, theFile);
         putObjectRequest.withMetadata(objectMetadata);*/


        // listen for progress updates and broadcast/notify them appropriately
        uploader.setProgressListener(new UploadProgressListener() {         
            @Override
            public void progressChanged(ProgressEvent progressEvent,
                    long bytesUploaded, int percentUploaded) {

                Notification notification = buildNotification(msg, percentUploaded);
                nm.notify(NOTIFY_ID_UPLOAD, notification);
                broadcastState(s3ObjectKey, percentUploaded, msg);
            }
        });

        // broadcast/notify that our upload is starting
        Notification notification = buildNotification(msg, 0);
        nm.notify(NOTIFY_ID_UPLOAD, notification);
        broadcastState(s3ObjectKey, 0, msg);

        try {
            String s3Location = uploader.start(); // initiate the upload
            broadcastState(s3ObjectKey, -1, "File successfully uploaded to " + s3Location);
        } catch (UploadIterruptedException uie) {
            broadcastState(s3ObjectKey, -1, "User interrupted");
        } catch (Exception e) {
            e.printStackTrace();
            broadcastState(s3ObjectKey, -1, "Error: " + e.getMessage());
        }
    }

    @Override
    public void onDestroy() {
        nm.cancel(NOTIFY_ID_UPLOAD);
        unregisterReceiver(uploadCancelReceiver);
        super.onDestroy();
    }

    private void broadcastState(String s3key, int percent, String msg) {
        Intent intent = new Intent(UPLOAD_STATE_CHANGED_ACTION);
        Bundle b = new Bundle();
        b.putString(S3KEY_EXTRA, s3key);
        b.putInt(PERCENT_EXTRA, percent);
        b.putString(MSG_EXTRA, msg);
        intent.putExtras(b);
        sendBroadcast(intent);
    }

    private Notification buildNotification(String msg, int progress) {  
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setWhen(System.currentTimeMillis());
        builder.setTicker(msg);
        builder.setContentTitle(getString(R.string.app_name));
        builder.setContentText(msg);
        builder.setSmallIcon(R.drawable.ic_stat_uploading);
        builder.setOngoing(true);
        builder.setProgress(100, progress, false);

        Intent notificationIntent = new Intent(this, MainActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        builder.setContentIntent(contentIntent);

        return builder.build();
    }

    private BroadcastReceiver uploadCancelReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (uploader != null) {
                uploader.interrupt();
            }
        }
    };

    private String md5(String s) {
        try {
            // create MD5 Hash
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

            // create Hex String
            StringBuffer hexString = new StringBuffer();
            for (int i=0; i<messageDigest.length; i++)
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

}

MainActivity.java

public class MainActivity extends Activity {

    private static final int FILE_SELECT_CODE = 0;

    Button select;
    Button interrupt;
    ProgressBar progress;
    TextView status;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        select = (Button) findViewById(R.id.btn_select);
        interrupt = (Button) findViewById(R.id.btn_interrupt);
        progress = (ProgressBar) findViewById(R.id.progress);
        status = (TextView) findViewById(R.id.status);

        select.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // start file chooser
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(
                        Intent.createChooser(intent, "Select a file to upload"),
                        FILE_SELECT_CODE);
            }
        });

        interrupt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // interrupt any active upload
                Intent intent = new Intent(UploadService.UPLOAD_CANCELLED_ACTION);
                sendBroadcast(intent);
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter f = new IntentFilter();
        f.addAction(UploadService.UPLOAD_STATE_CHANGED_ACTION);
        registerReceiver(uploadStateReceiver, f);
    }

    @Override
    protected void onStop() {
        unregisterReceiver(uploadStateReceiver);
        super.onStop();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FILE_SELECT_CODE) {
            if (resultCode == RESULT_OK) {  
                // get path of selected file 
                Uri uri = data.getData();
                String path = getPathFromContentUri(uri);
                Log.d("S3", "uri=" + uri.toString());
                Log.d("S3", "path=" + path);
                // initiate the upload
                Intent intent = new Intent(this, UploadService.class);
                intent.putExtra(UploadService.ARG_FILE_PATH, path);
                startService(intent);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private String getPathFromContentUri(Uri uri) {
        String path = uri.getPath();
        if (uri.toString().startsWith("content://")) {
            String[] projection = { MediaStore.MediaColumns.DATA };
            ContentResolver cr = getApplicationContext().getContentResolver();
            Cursor cursor = cr.query(uri, projection, null, null, null);
            if (cursor != null) {
                try {
                    if (cursor.moveToFirst()) {
                        path = cursor.getString(0);
                    }
                } finally {
                    cursor.close();
                }
            }

        }
        return path;
    }

    private BroadcastReceiver uploadStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle b = intent.getExtras();
            status.setText(b.getString(UploadService.MSG_EXTRA));
            int percent = b.getInt(UploadService.PERCENT_EXTRA);
            progress.setIndeterminate(percent < 0);
            progress.setProgress(percent);
        }
    };

}

1 个答案:

答案 0 :(得分:1)

看起来您正在从Github https://github.com/jgilfelt/android-simpl3r运行示例。 SDK版本1.4.3于3年前发布。它使用Android内置的Apache HttpClient,它非常多,并且已被Android弃用。内容已被消费&#39;问题有时会发生。

请将SDK更新到最新版本v2.2.2。它应该向后兼容。请查看http://aws.amazon.com/mobile/sdk/