我試圖用HttpURLConnection
類的幫助打開連接。http URL連接無法處理重定向
我試過這段代碼來處理一個URL,但看到日誌,我發現它無法獲取重定向的URL。在示例代碼中,您會看到爲了獲取URL,我使用了一個while
循環,並且由於它記錄了相同的URL。我急切地尋找解決問題的更好方法。我希望問題清楚。
下面是示例代碼,我使用: -
Log.d(TAG,"URL received : --- >"+downloadURL);
URL url=new URL(downloadURL);
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setInstanceFollowRedirects(true);
httpURLConnection.connect();
Log.d(TAG,httpURLConnection.getResponseMessage()+" Append with "+httpURLConnection.getResponseCode());
while(httpURLConnection.getResponseCode()==HttpURLConnection.HTTP_MOVED_PERM)
{
httpURLConnection.getInputStream();
URL url1=httpURLConnection.getURL();
Log.d(TAG,"Redirected URL = "+url1);
}
InputStream inptStream=httpURLConnection.getInputStream();
這裏是logcat的輸出: -
03-08 13:28:38.814 22597-23668/abhirojpanwar.tablayout D/AsyncImageDownloader: Redirected URL = https://unsplash.com/photos/65sru5g6xHk/download
03-08 13:28:38.814 22597-23668/abhirojpanwar.tablayout D/AsyncImageDownloader: Redirected URL = https://unsplash.com/photos/65sru5g6xHk/download
03-08 13:28:38.814 22597-23668/abhirojpanwar.tablayout D/AsyncImageDownloader: Redirected URL = https://unsplash.com/photos/65sru5g6xHk/download
03-08 13:28:38.814 22597-23668/abhirojpanwar.tablayout D/AsyncImageDownloader: Redirected URL = https://unsplash.com/photos/65sru5g6xHk/download
03-08 13:28:38.814 22597-23668/abhirojpanwar.tablayout D/AsyncImageDownloader: Redirected URL = https://unsplash.com/photos/65sru5g6xHk/download
03-08 13:28:38.814 22597-23668/abhirojpanwar.tablayout D/AsyncImageDownloader: Redirected URL = https://unsplash.com/photos/65sru5g6xHk/download
03-08 13:28:38.814 22597-23668/abhirojpanwar.tablayout D/AsyncImageDownloader: Redirected URL = https://unsplash.com/photos/65sru5g6xHk/download
03-08 13:28:38.814 22597-23668/abhirojpanwar.tablayout D/AsyncImageDownloader: Redirected URL = https://unsplash.com/photos/65sru5g6xHk/download
03-08 13:28:38.814 22597-23668/abhirojpanwar.tablayout D/AsyncImageDownloader: Redirected URL = https://unsplash.com/photos/65sru5g6xHk/download
03-08 13:28:38.815 22597-23668/abhirojpanwar.tablayout D/AsyncImageDownloader: Redirected URL = https://unsplash.com/photos/65sru5g6xHk/download
03-08 13:28:38.815 22597-23668/abhirojpanwar.tablayout D/AsyncImageDownloader: Redirected URL = https://unsplash.com/photos/65sru5g6xHk/download
03-08 13:28:38.815 22597-23668/abhirojpanwar.tablayout D/AsyncImageDownloader: Redirected URL = https://unsplash.com/photos/65sru5g6xHk/download
03-08 13:28:38.815 22597-23668/abhirojpanwar.tablayout D/AsyncImageDownloader: Redirected URL = https://unsplash.com/photos/65sru5g6xHk/download
對不起,我可能還沒有明白,但究竟是獲取200響應與重定向的URL? –
默認情況下,'setFollowRedirects'爲true,這意味着它會自動重定向到新的URL並返回從它接收到的響應(200)。 –
因此將其設置爲false,我將其設置爲不檢查URL重定向,我將在後面在循環中做我自己,對吧? –