@Override public String getRedirectLocation() { final Response priorRes = response.priorResponse(); if (priorRes != null && response.isSuccessful() && RedirectUtil.isRedirect(priorRes.code())) { // prior response is a redirect response, so current response // has redirect location return response.request().url().toString(); } return null; }
@Override public void handleRedirect( DownloadConnection originalConnection, DownloadConnection.Connected originalConnected, Map<String, List<String>> headerProperties) throws IOException { int responseCode = originalConnected.getResponseCode(); int redirectCount = 0; final DownloadUrlConnection downloadUrlConnection = (DownloadUrlConnection) originalConnection; while (RedirectUtil.isRedirect(responseCode)) { // the last connect is useless, so release it downloadUrlConnection.release(); if (++redirectCount > RedirectUtil.MAX_REDIRECT_TIMES) { throw new ProtocolException("Too many redirect requests: " + redirectCount); } redirectLocation = RedirectUtil .getRedirectedUrl(originalConnected, responseCode); downloadUrlConnection.url = new URL(redirectLocation); downloadUrlConnection.configUrlConnection(); Util.addRequestHeaderFields(headerProperties, downloadUrlConnection); downloadUrlConnection.connection.connect(); responseCode = downloadUrlConnection.getResponseCode(); } }
@Test public void getRedirectUrl() throws IOException { final String redirectUrl = "http://redirect"; final DownloadConnection.Connected connected = mock(DownloadConnection.Connected.class); when(connected.getResponseHeaderField("Location")).thenReturn(redirectUrl); assertEquals(RedirectUtil.getRedirectedUrl(connected, 302), redirectUrl); }
@Test public void getRedirectedUrl_thrownProtocolException() throws IOException { thrown.expect(ProtocolException.class); thrown.expectMessage("Response code is 302 but can't find Location field"); final DownloadConnection.Connected connected = mock(DownloadConnection.Connected.class); when(connected.getResponseHeaderField("Location")).thenReturn(null); RedirectUtil.getRedirectedUrl(connected, 302); }
@Test public void isRedirect() { assertTrue(RedirectUtil.isRedirect(HttpURLConnection.HTTP_MOVED_PERM)); assertTrue(RedirectUtil.isRedirect(HttpURLConnection.HTTP_MOVED_TEMP)); assertTrue(RedirectUtil.isRedirect(HttpURLConnection.HTTP_SEE_OTHER)); assertTrue(RedirectUtil.isRedirect(HttpURLConnection.HTTP_MULT_CHOICE)); assertTrue(RedirectUtil.isRedirect(RedirectUtil.HTTP_TEMPORARY_REDIRECT)); assertTrue(RedirectUtil.isRedirect(RedirectUtil.HTTP_PERMANENT_REDIRECT)); assertFalse(RedirectUtil.isRedirect(HttpsURLConnection.HTTP_ACCEPTED)); }