Android:从AmazonS3下载文件时出现异常

时间:2012-08-30 06:02:09

标签: android amazon-s3 download

在我的Android应用程序中,当我尝试从Amazon S3下载图像文件时,它给了我异常

这是例外:

08-30 11:20:34.157: W/System.err(6519): android.os.NetworkOnMainThreadException
08-30 11:20:34.157: W/System.err(6519): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
08-30 11:20:34.157: W/System.err(6519):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
08-30 11:20:34.157: W/System.err(6519):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
08-30 11:20:34.157: W/System.err(6519):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
08-30 11:20:34.157: W/System.err(6519):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-30 11:20:34.168: W/System.err(6519):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-30 11:20:34.168: W/System.err(6519):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-30 11:20:34.168: W/System.err(6519):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-30 11:20:34.177: W/System.err(6519):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-30 11:20:34.177: W/System.err(6519):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-30 11:20:34.177: W/System.err(6519):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-30 11:20:34.177: W/System.err(6519):     at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:285)
08-30 11:20:34.177: W/System.err(6519):     at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:167)
08-30 11:20:34.187: W/System.err(6519):     at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:2781)
08-30 11:20:34.187: W/System.err(6519):     at com.amazonaws.services.s3.AmazonS3Client.getObject(AmazonS3Client.java:872)
08-30 11:20:34.187: W/System.err(6519):     at com.example.amazons3.AmazonS3DemoActivity.Download(AmazonS3DemoActivity.java:74)
08-30 11:20:34.187: W/System.err(6519):     at java.lang.reflect.Method.invokeNative(Native Method)
08-30 11:20:34.187: W/System.err(6519):     at java.lang.reflect.Method.invoke(Method.java:511)
08-30 11:20:34.187: W/System.err(6519):     at android.view.View$1.onClick(View.java:3039)
08-30 11:20:34.197: W/System.err(6519):     at android.view.View.performClick(View.java:3511)
08-30 11:20:34.197: W/System.err(6519):     at android.view.View$PerformClick.run(View.java:14105)
08-30 11:20:34.197: W/System.err(6519):     at android.os.Handler.handleCallback(Handler.java:605)
08-30 11:20:34.197: W/System.err(6519):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-30 11:20:34.207: W/System.err(6519):     at android.os.Looper.loop(Looper.java:137)
08-30 11:20:34.207: W/System.err(6519):     at android.app.ActivityThread.main(ActivityThread.java:4424)
08-30 11:20:34.207: W/System.err(6519):     at java.lang.reflect.Method.invokeNative(Native Method)
08-30 11:20:34.207: W/System.err(6519):     at java.lang.reflect.Method.invoke(Method.java:511)
08-30 11:20:34.217: W/System.err(6519):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-30 11:20:34.227: W/System.err(6519):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-30 11:20:34.227: W/System.err(6519):     at dalvik.system.NativeStart.main(Native Method)

这是我的java代码:

public class AmazonS3Activity extends Activity 
{
private String Tag = "Downlaod";

Button btnDownload;

Context myContext;

String product_code = "pro_code";

String bucketName = "bucketnamw";

String appDirPath = Environment.getExternalStorageDirectory().getName() +"/foldername/";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    myContext = this;

    btnDownload = (Button) findViewById(R.id.btnDownload);      
}

public void Download(View button)
{
    try 
    {
        String imgName = product_code+"1.jpg";
        String md5Name = getMD5HasCode(product_code);

        String productCode = md5Name+".app/";

        String filePath = getFullFilePath(imgName);

        String accessKey = "accessKey";
        String secretKey = "secretKey";
        AWSCredentials credential = new BasicAWSCredentials(accessKey, secretKey);

        Log.e(Tag, "FileName : " + filePath, null);

        String strObjectKey = productCode + imgName.replace(product_code,md5Name);

        Log.e(Tag, "Object Key : " + strObjectKey, null);

        GetObjectRequest objRequest = new GetObjectRequest(bucketName,strObjectKey);

        AmazonS3Client myS3Client = new AmazonS3Client(credential);

        S3Object s3Object = myS3Client.getObject(objRequest);

        long fileSize = s3Object.getObjectMetadata().getContentLength();
        final InputStream input = s3Object.getObjectContent();
        final FileOutputStream fos = new FileOutputStream(filePath);

        long total = 0;
        int len=0;

        byte[] buf = new byte[1024];

        while((len = input.read(buf)) > 0)
        {
            fos.write(buf,0,len);

            total = total + len;
        }

        if(len == -1 && total==fileSize)
        {
            Thread.currentThread().interrupt();

            input.close();
            fos.close();

        }

    } 
    catch (Exception e) 
    {
        e.printStackTrace();
        Log.e(Tag, "Error Key : " + e.getMessage(), null);
    }

}

public String getMD5HasCode(String strMessage)
{
    try
    {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        byte[] messageDigestBytes = messageDigest.digest(strMessage.getBytes());
        BigInteger hasNumber = new BigInteger(1,messageDigestBytes);
        String md5 = hasNumber.toString(16);

        while(md5.length()<32)
        {
            md5 = "0" + md5;
        }

        return md5;
    }
    catch (Exception ex) 
    {
        Toast.makeText(myContext, "ERROR in HasCode : "+ex.toString(), Toast.LENGTH_SHORT).show();  
        return null;
    }
}

public String getFullFilePath(String filename)
{
    File dir = new File(appDirPath);
    if(!dir.exists())
    {
        dir.mkdir();
    }
    return appDirPath+filename;
}
 }

1 个答案:

答案 0 :(得分:3)

截至发现的文件here

  

当应用程序尝试执行时,抛出NetworkOnMainThreadException   在其主线程上进行网络操作。

     

这仅适用于针对Honeycomb SDK或。的应用程序   更高。允许使用早期SDK版本的应用程序   他们的主要事件循环线程上的网络,但它是很重要的   气馁。

解决方案可以使用AsyncTask进行与网络相关的操作。