gpt4 book ai didi

java - Android Studio FTP文件上传

转载 作者:行者123 更新时间:2023-12-01 11:07:40 24 4
gpt4 key购买 nike

所以我正在开发一个应用程序来接收文件并将其上传到 FTP 服务器,但我不断收到 android.os.NetworkOnMainThreadException。有想法该怎么解决这个吗?这是我的代码

    public void sendData() throws Exception {
FTPUploader stuff = new FTPUploader("xxx","xxx","xxx");
stuff.doInBackground();
}

FTPUploader 类:

    import android.os.AsyncTask;

import org.apache.commons.net.ftp.FTPClient;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetAddress;

public class FTPUploader extends AsyncTask<String, Void, Void> {
//@Override
protected Void doInBackground(String... params) {
FTPClient con = new FTPClient();
try {

con.connect(InetAddress.getByName(params[0]));

if (con.login(params[1], params[2])) {
con.enterLocalPassiveMode();
String data = params[3];
ByteArrayInputStream in = new ByteArrayInputStream(data.getBytes());
boolean result = con.storeFile(params[4], in);
in.close();
if (result) {
System.out.println("upload result: " + result);
}
}
} catch (Exception e) {
e.printStackTrace();
}

try {
con.logout();
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}

return null;
}
}

最佳答案

您需要从主 Activity 或类中调用,而不是 doInBackground ()

new FTPUploader().execute(param1,param2,param3);

关于java - Android Studio FTP文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32772456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com