其他分享
首页 > 其他分享> > Android:从AmazonS3下载文件时出现异常

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

作者:互联网

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

这里是例外:

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

解决方法:

截至文档发现here.

NetworkOnMainThreadException is thrown when an application attempts to perform a
networking operation on its main thread.

This is only thrown for applications targeting the Honeycomb SDK or
higher. Applications targeting earlier SDK versions are allowed to do
networking on their main event loop threads, but it’s heavily
discouraged.

该解决方案可以将AsyncTask用于与网络相关的操作.

标签:download,amazon-s3,android
来源: https://codeday.me/bug/20191127/2076353.html