Android Studio - Java 几天来我一直在尝试从我的网站读取文本文件。 网上找的例子都行不通。 “Error”总是在“catch”中输出(参见下面的代码)。 URL 的路径是正确的。我用下载测试了一下。 已添加互联网权限。 问题出在哪里?
try{
URL yahoo = new URL("https://www.robl.de/data/HS.txt");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
catch ( IOException e ) {
e.printStackTrace();
inputLine="error";
}
try{
URL llll = new URL("http://www.robl.de/data/HS.txt");
URLConnection conLLL = llll.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader( conLLL.getInputStream()));
while ( ( strLine = br.readLine() ) != null)
System.out.println(strLine);
br.close();
}
catch(Exception ex)
{
ex.printStackTrace();
strLine="error";
}
听起来您遇到了 NetworkOnMainThreadException,当尝试在 Android UI 线程上执行网络操作时会发生这种情况。 Android 要求在后台线程上发出网络请求。以下是如何修改代码以使用 AsyncTask 在后台线程上执行网络操作:
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class NetworkFileReader extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urlString) {
StringBuilder content = new StringBuilder();
try {
URL url = new URL(urlString[0]);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line).append("\n");
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
return "Error: " + e.getMessage();
}
return content.toString();
}
@Override
protected void onPostExecute(String result) {
// This is where you would handle the result of the network operation
// For example, updating the UI or storing the data
System.out.println(result);
}
}
// Usage:
new NetworkFileReader().execute("https://www.robl.de/data/HS.txt");
确保在您的 Activity 或片段中正确执行此 AsyncTask,并在 onPostExecute 方法中处理结果。
另外,请确保您的 AndroidManifest.xml 中具有互联网权限:
<uses-permission android:name="android.permission.INTERNET" />
请注意,AsyncTask 在 API 级别 30 及更高版本中已弃用。对于现代 Android 开发,c
enter code here
考虑使用 Kotlin 协程或 Java 并发实用程序(例如 Executors)。然而,AsyncTask 仍然是出于教育目的或在遗留代码库中快速解决此问题的有效方法。