Перенаправление HttpURLConnection
– это просто индикатор, на самом деле он не поможет вам выполнить “реальное” перенаправление http, вам все равно нужно обработать его вручную.
URL obj = new URL(url); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); conn.setInstanceFollowRedirects(true); //you still need to handle redirect manully. HttpURLConnection.setFollowRedirects(true);
1. Пример перенаправления Java Http
Если сервер перенаправляется с исходного URL-адреса на другой URL-адрес, код ответа должен быть 301: Перемещен навсегда или 302: Временное перенаправление . И вы можете получить новый перенаправленный URL-адрес, прочитав заголовок ” Местоположение ” заголовка HTTP-ответа.
Например, доступ к обычному веб–сайту HTTP twitter – http://www.twitter.com , он автоматически перенаправит на веб-сайт HTTPS twitter – https://www.twitter.com .
package com.mkyong.http; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpRedirectExample { public static void main(String[] args) { try { String url = "http://www.twitter.com"; URL obj = new URL(url); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); conn.setReadTimeout(5000); conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8"); conn.addRequestProperty("User-Agent", "Mozilla"); conn.addRequestProperty("Referer", "google.com"); System.out.println("Request URL ... " + url); boolean redirect = false; // normally, 3xx is redirect int status = conn.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } System.out.println("Response Code ... " + status); if (redirect) { // get redirect url from "location" header field String newUrl = conn.getHeaderField("Location"); // get the cookie if need, for login String cookies = conn.getHeaderField("Set-Cookie"); // open the new connnection again conn = (HttpURLConnection) new URL(newUrl).openConnection(); conn.setRequestProperty("Cookie", cookies); conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8"); conn.addRequestProperty("User-Agent", "Mozilla"); conn.addRequestProperty("Referer", "google.com"); System.out.println("Redirect to URL : " + newUrl); } BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer html = new StringBuffer(); while ((inputLine = in.readLine()) != null) { html.append(inputLine); } in.close(); System.out.println("URL Content... \n" + html.toString()); System.out.println("Done"); } catch (Exception e) { e.printStackTrace(); } } }
Выход
Request URL ... http://www.twitter.com Response Code ... 301 Redirect to URL : https://twitter.com/ URL Content...<\/div>window.yaContextCb.push(()=>{ Ya.Context.AdvManager.render({ renderTo: 'yandex_rtb_R-A-995040-7', blockId: 'R-A-995040-7' })})<\/scr"+"ipt>"; cachedBlocksArray[258393] = " <\/div>window.yaContextCb.push(()=>{ Ya.Context.AdvManager.render({ renderTo: 'yandex_rtb_R-A-995040-6', blockId: 'R-A-995040-6' })})<\/scr"+"ipt>"; cachedBlocksArray[258094] = " <\/div>window.yaContextCb.push(()=>{ Ya.Context.AdvManager.render({ renderTo: 'yandex_rtb_R-A-995040-1', blockId: 'R-A-995040-1' })})<\/scr"+"ipt>"; cachedBlocksArray[258097] = " <\/div>window.yaContextCb.push(()=>{ Ya.Context.AdvManager.renderWidget({ renderTo: 'id-C-A-995040-4', blockId: 'C-A-995040-4' })})<\/scr"+"ipt>"; cachedBlocksArray[258095] = " <\/div>window.yaContextCb.push(()=>{ Ya.Context.AdvManager.render({ renderTo: 'yandex_rtb_R-A-995040-3', blockId: 'R-A-995040-3' })})<\/scr"+"ipt>"; cachedBlocksArray[258093] = " <\/div>window.yaContextCb.push(()=>{ Ya.Context.AdvManager.render({ renderTo: 'yandex_rtb_R-A-995040-5', blockId: 'R-A-995040-5' })})<\/scr"+"ipt>";