2016-05-16 15 views
0

我的android應用程序可以從一個特定的文件模式(如* .pdf)從網址下載文件。如何知道文件無法在java/android中未經授權下載?

但是一些網址需要用戶的授權才能下載文件。我不想顯示這些網址的授權屏幕。我只是想傳達給用戶這個文件不能被這個應用程序下載。

我該如何在java/android中執行此操作?

void download(String url) 
{ 
    URL url = new URL(url); 
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

    //TODO : stop download if detected that this url requires authorization/authentication. 

    urlConnection.disconnect(); 
} 
+0

檢查您嘗試下載時獲得的[http status](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes)? – 2016-05-16 06:48:34

+0

獲取該網址的http響應代碼,如果是401則顯示登錄頁面。 – Gangaraju

+0

m將響應碼作爲-1而不是401. :( –

回答

0

請從響應中獲取HTTP狀態,如下所示。

URL url = new URL("http://example.com"); 
HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
connection.setRequestMethod("GET");//Or POST, depending on your service 
connection.connect(); 

int code = connection.getResponseCode(); 

如果您的Web服務是Restful服務,則應該返回401。

相關問題