在android中将文件上传到Dropbox,putFile方法抛出异常

时间:2014-10-23 20:57:12

标签: android exception file-upload dropbox-api

我尝试使用Dropbox API tutorial将文件上传到Dropbox。我在创建Activity时登录,并且我在onResume()方法中添加了一些代码,如教程中所述。然后,在单击按钮后,将调用startService()方法。

当它到达" com.dropbox.client2.DropboxAPI.Entry响应= mDBApi.putFile(" /working-draft.txt" ;, inputStream,file.length(),null ,null);",应用程序抛出异常(不是DropboxException,也不是DropboxUnlinkedException,......它只是进入catch异常块)。

知道可能出现什么问题吗?

这是我的代码:

private final static String APP_KEY = "xxxxxxxxxxxxx";
private final static String APP_SECRET = "xxxxxxxxxxxxx";
private DropboxAPI<AndroidAuthSession> mDBApi;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
    AndroidAuthSession session = new AndroidAuthSession(appKeys);   
    mDBApi = new DropboxAPI<AndroidAuthSession>(session);
    AndroidAuthSession s = mDBApi.getSession();
    s.startOAuth2Authentication(MainActivity.this);
}

@Override
protected void onResume() {
    super.onResume();
    if (mDBApi.getSession().authenticationSuccessful()) {
        try {
            // Required to complete auth, sets the access token on the session
            mDBApi.getSession().finishAuthentication();

            String accessToken = mDBApi.getSession().getOAuth2AccessToken();
        } catch (IllegalStateException e) {
            Log.i("DbAuthLog", "Error authenticating", e);
        }
    }

}

public void startService(View v) {    

    String text = "Hello world";
    String filePath = Environment.getExternalStorageDirectory() + "/working-draft.txt";
    Log.i("SERVICE", filePath);
    File file = new File(filePath);
    try {
        if(!file.exists()){
            file.createNewFile();
        }
        BufferedWriter output = new BufferedWriter(new FileWriter(file));
        output.write(text);
        output.close();
        FileInputStream inputStream = new FileInputStream(file);
        com.dropbox.client2.DropboxAPI.Entry response = mDBApi.putFile("/working-draft.txt", inputStream, file.length(), null, null);
        Log.i("DbExampleLog", "The uploaded file's rev is: " + response.rev);
    }
    catch(DropboxUnlinkedException e){
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        Log.i("Exception", errors.toString());
    }
    catch(DropboxFileSizeException e){
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        Log.i("Exception", errors.toString());
    }
    catch(DropboxServerException e){
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        Log.i("Exception", errors.toString());
    }
    catch(DropboxIOException e){
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        Log.i("Exception", errors.toString());
    }
    catch (DropboxException e){
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        Log.i("Exception", errors.toString());
    }
    catch (Exception e) {
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        Log.i("Exception", errors.toString());
    }
}

这是我得到的stackTrace:

10-23 22:42:34.254: I/Exception(28082): android.os.NetworkOnMainThreadException
10-23 22:42:34.254: I/Exception(28082):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
10-23 22:42:34.254: I/Exception(28082):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
10-23 22:42:34.254: I/Exception(28082):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
10-23 22:42:34.254: I/Exception(28082):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
10-23 22:42:34.254: I/Exception(28082):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
10-23 22:42:34.254: I/Exception(28082):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
10-23 22:42:34.254: I/Exception(28082):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
10-23 22:42:34.254: I/Exception(28082):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
10-23 22:42:34.254: I/Exception(28082):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
10-23 22:42:34.254: I/Exception(28082):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-23 22:42:34.254: I/Exception(28082):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-23 22:42:34.254: I/Exception(28082):     at com.dropbox.client2.RESTUtility.execute(RESTUtility.java:387)
10-23 22:42:34.254: I/Exception(28082):     at com.dropbox.client2.DropboxAPI$BasicUploadRequest.upload(DropboxAPI.java:1119)
10-23 22:42:34.254: I/Exception(28082):     at com.dropbox.client2.DropboxAPI.putFile(DropboxAPI.java:1460)
10-23 22:42:34.254: I/Exception(28082):     at com.example.example.MainActivity.startService(MainActivity.java:81)
10-23 22:42:34.254: I/Exception(28082):     at java.lang.reflect.Method.invokeNative(Native Method)
10-23 22:42:34.254: I/Exception(28082):     at java.lang.reflect.Method.invoke(Method.java:525)
10-23 22:42:34.254: I/Exception(28082):     at android.view.View$1.onClick(View.java:3628)
10-23 22:42:34.254: I/Exception(28082):     at android.view.View.performClick(View.java:4240)
10-23 22:42:34.254: I/Exception(28082):     at android.view.View$PerformClick.run(View.java:17721)
10-23 22:42:34.254: I/Exception(28082):     at android.os.Handler.handleCallback(Handler.java:730)
10-23 22:42:34.254: I/Exception(28082):     at android.os.Handler.dispatchMessage(Handler.java:92)
10-23 22:42:34.254: I/Exception(28082):     at android.os.Looper.loop(Looper.java:137)
10-23 22:42:34.254: I/Exception(28082):     at android.app.ActivityThread.main(ActivityThread.java:5103)
10-23 22:42:34.254: I/Exception(28082):     at java.lang.reflect.Method.invokeNative(Native Method)
10-23 22:42:34.254: I/Exception(28082):     at java.lang.reflect.Method.invoke(Method.java:525)
10-23 22:42:34.254: I/Exception(28082):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-23 22:42:34.254: I/Exception(28082):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-23 22:42:34.254: I/Exception(28082):     at dalvik.system.NativeStart.main(Native Method)

提前致谢。

2 个答案:

答案 0 :(得分:2)

您正在获得NetworkOnMainThreadException,这意味着您正在尝试在主线程上进行网络呼叫,这在Android上是不允许的。 (putFile方法对Dropbox API服务器进行网络调用以发送文件内容。)您应该在后台线程上进行此调用。关于如何执行此操作还有其他答案,例如:How to fix android.os.NetworkOnMainThreadException?

答案 1 :(得分:0)

好的,非常感谢格雷格。它完全符合您分享的链接中的指示。我使用了另一个扩展AsyncTask的类,就像完成了in this post,“使用Android SDK将文件上传到Dropbox”一节。