我一生都無法弄清楚從 url 檢索文本檔案并讀取其內容的最簡單任務。我找到的所有代碼都是 5-12 歲的,并且不起作用。由于 android api 30 主執行緒上的任何網路請求都會給出 android.os.NetworkOnMainThreadException。我被困在這部分使用 kotlin。
我不能使用下載管理器(除非有辦法臨時存盤檔案并檢索內容),因為檔案不需要下載到本地存盤只讀。我看到的最接近的來自: Android - 如何從 url 讀取文本檔案?
try {
// Create a URL for the desired page
URL url = new URL("mysite.com/thefile.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
但是這段代碼不起作用。
uj5u.com熱心網友回復:
所以三天后想跳崖。我找到了答案。當然,這是在這里提出問題后的幾分鐘(第一個問題,請善待。)。唯一的問題是您在檢索檔案的服務器上需要一個用于 HTTPS 的 SSL 證書。我的服務器是http,但我可以在那里獲得證書并修復它。為了測驗,我拋出了一個 github 存盤庫并鏈接到原始文本檔案。這是我的解決方案,如果這可以節省您 3 天的時間為我倒一個。
Thread {
try {
val url = URL("https://raw.githubusercontent.com/USERNAME/NeedHTTPSdontWanaSSL/main/info.txt")
val uc: HttpsURLConnection = url.openConnection() as HttpsURLConnection
val br = BufferedReader(InputStreamReader(uc.getInputStream()))
var line: String?
val lin2 = StringBuilder()
while (br.readLine().also { line = it } != null) {
lin2.append(line)
}
Log.d("The Text", "$lin2")
} catch (e: IOException) {
Log.d("texts", "onClick: " e.getLocalizedMessage())
e.printStackTrace()
}
}.start()
信用:2018 年 8 月 12 日 9:29 Aishik kirtaniya Android - 如何從 url 讀取文本檔案?
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/517813.html
標籤:安卓科特林网址文本
