![](/img/trans.png)
[英]How to download file from an URL inside a JSON in Android Studio
[英]Android - download JSON file from url
是否可以從 URL 下載包含 JSON 數據的文件? 此外,我需要獲取的文件沒有文件擴展名,這是一個問題還是我可以在下載時強制它具有 .txt 擴展名?
更新:我忘了提及,該網站需要輸入用戶名和密碼才能訪問我知道的網站。 有沒有辦法在我檢索文件時輸入這些值?
您是否嘗試過使用 URLConnection?
private InputStream getStream(String url) {
try {
URL url = new URL(url);
URLConnection urlConnection = url.openConnection();
urlConnection.setConnectTimeout(1000);
return urlConnection.getInputStream();
} catch (Exception ex) {
return null;
}
}
還要記住像這樣編碼你的參數:
String action="blabla";
InputStream myStream=getStream("http://www.myweb.com/action.php?action="+URLEncoder.encode(action));
基本上你會做這樣的事情:
代碼:
URL address = URL.parse("http://yoururlhere.com/yourfile.txt");
URLConnection conn = new URLConnection(address);
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer bab = new ByteArrayBuffer(64);
int current = 0;
while((current = bis.read()) != -1) {
bab.append((byte)current);
}
FileOutputStream fos = new FileOutputStream(new File(filepath));
fos.write(bab.toByteArray());
fos.close();
當然。 就像其他人指出的那樣,基本 URL 是一個足夠好的起點。
雖然其他代碼示例有效,但 JSON 內容的實際訪問可以是單行的。 使用Jackson JSON 庫,您可以執行以下操作:
Response resp = new ObjectMapper().readValue(new URL("http://dot.com/api/?customerId=1234").openStream(),Response.class);
如果您想將 JSON 數據綁定到您定義的“響應”中:要獲取地圖,您應該這樣做:
Map<String,Object> map = new ObjectMapper().readValue(new URL("http://dot.com/api/?customerId=1234").openStream(), Map.class);
關於添加用戶信息; 這些通常使用Basic Auth傳遞,其中您將 base64 編碼的用戶信息作為“授權”標頭傳遞。 為此,您需要從 URL 打開 HttpURLConnection,並添加標題; JSON 訪問部分仍然相同。
這是我編寫的一個類文件和一個接口,用於從 URL 下載 JSON 數據。 至於用戶名密碼驗證,這將取決於它在您訪問的網站上的實現方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.