簡體   English   中英

如何知道在Java / Android中未經授權無法從其網址下載文件?

[英]How to know a file cannot be downloaded from its url without authorization in java/android?

我的Android應用程序可以從具有特定文件格式(例如* .pdf)的url下載文件。

但是有些網址需要用戶授權才能下載文件。 我不想顯示此類網址的授權屏幕。 我只想向用戶傳達此應用程序無法下載此文件。

我如何在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();
}

請從響應中獲取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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM