简体   繁体   English

无法在Android中连接到FTP

[英]Unable to connect to FTP in Android

I've checked the other answers and they didn't help me with this error. 我检查了其他答案,但他们没有帮助我解决此错误。 Maybe I'm doing something else wrong. 也许我做错了其他事情。

Here's my code: 这是我的代码:

    void uploadPic() throws FileNotFoundException
{
    FileInputStream fis = new FileInputStream(path);
    FTPClient con = new FTPClient();
    int bytesAvailable;
    try
    {
        con.connect("ftp://ftp.drivehq.com/");
        Toast.makeText(this, "Connected to FTP", Toast.LENGTH_SHORT).show();
        if (con.login("x", "x"))
        {
            Toast.makeText(this, "Logged in", Toast.LENGTH_SHORT).show();
            con.enterLocalPassiveMode(); // Active mode doesn't really work on Android
            bytesAvailable = fis.available();
            byte[] barray = new byte[bytesAvailable];
            fis.read(barray);
            ByteArrayInputStream in = new ByteArrayInputStream(barray);
            boolean result = con.storeFile("/CameraUpload.jpg", in);
            in.close();
            if (result) Log.v("Upload Result", "Succeeded");
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

I've added INTERNET permission to my project. 我已将INTERNET权限添加到我的项目中。 The logcat shows these errors: 日志显示以下错误:

android.os.NetworkOnMainThreadException
W/System.err(17531):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
W/System.err(17531):    at java.net.InetAddress.lookupHostByName(InetAddress.java:391

I'm connected to the internet via Wifi. 我通过Wifi连接到互联网。

That exception seems to be thrown when you try to perform network operations (such as FTP) from your main thread. 当您尝试从主线程执行网络操作(例如FTP)时,似乎抛出了该异常。 This is not allowed for performance reasons (so that the application doesn't appear to lock up to the user, when performing an action which may take a while). 由于性能原因,这是不允许的(因此,在执行可能需要一段时间的操作时,应用程序似乎不会锁定用户)。 Assuming you are using Honeycomb or higher, you would need to move the code that makes the connection into its own child thread. 假设您使用的是Honeycomb或更高版本,则需要将建立连接的代码移到其自己的子线程中。

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

http://developer.android.com/guide/practices/design/responsiveness.html http://developer.android.com/guide/practices/design/sensitiveness.html

Most likely, this error means that your device cannot resolve ftp.drivehq.com to its IP address. 此错误很可能表示您的设备无法将ftp.drivehq.com解析为其IP地址。 I can't say for sure because you only pasted part of the error log. 我不能肯定地说,因为您仅粘贴了错误日志的一部分。 Make sure you have network connection and that your DNS is working correctly. 确保您具有网络连接,并且您的DNS正常运行。 See if you can connect to this same site via android browser, for example. 例如,看看是否可以通过android浏览器连接到同一站点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM