Come ottenere l'URL sostituito/reindirizzato dal codice java
Durante l'analisi di una pagina web, ottengo il link href = http://www.onvista.de/aktien/snapshot.html?ID_OSI=36714349 Quando si emette questo link nel mio browser, lo sostituisce con " http://www.onvista.de/aktien/Adidas-Aktie-DE000A1EWWW0 " e lo rende correttamente. Ma con java non riesco a recuperare la pagina. Ho usato il seguente esempio che è stato suggerito qui per visualizzare gli URL reindirizzati.
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class GetRedirected {
public GetRedirected() throws MalformedURLException, IOException {
String url="http://www.onvista.de/aktien/snapshot.html?ID_OSI=36714349";
URLConnection con = new URL( url ).openConnection();
System.out.println( "orignal url: " + con.getURL() );
con.connect();
System.out.println( "connected url: " + con.getURL() );
InputStream is = con.getInputStream();
System.out.println( "redirected url: " + con.getURL() );
is.close();
}
public static void main(String[] args) throws Exception {
new GetRedirected();
}
}
Ma fallisce all'istruzione "InputStream is ="con il messaggio di errore allegato. Come posso risolvere questo. Qualsiasi idea è benvenuta.
Url originale: www.onvista.de/aktien/snapshot.html?ID_OSI=36714349
Url connesso: www.onvista.de/aktien/snapshot.html?ID_OSI=36714349
Eccezione nel thread" principale " java. io. IOException: il server ha restituito HTTP
Codice di risposta: 403 per l'URL: www.onvista.de/aktien/snapshot.html?ID_OSI=36714349
Su sun. net. www. protocol. http. HttpURLConnection. getInputStream (Fonte sconosciuta)
A de.gombers.broker....
2 answers
Errore molto comune: quando il codice di stato HTTP di una risposta di HttpURLConnection
indica un errore (AFAIK >= 400), l'accesso a getInputStream()
genera un'eccezione. Devi controllare getResponseCode()
e poi decidere se devi chiamare getInputStream()
o getErrorStream()
. Quindi, invece di chiamare getInputStream()
, dovresti prima chiamare getResponseCode()
.
Ma in realtà non riesco a riprodurre il tuo errore, per me funziona (anche se uso una piccola libreria di astrazione chiamata DavidWebb :
public void testAktienAdidas() throws Exception {
Webb webb = Webb.create();
Response<String> response = webb
.get("http://www.onvista.de/aktien/snapshot.html?ID_OSI=36714349")
.asString();
assertEquals(200, response.getStatusCode());
assertNotNull(response.getBody());
assertTrue(response.getBody().contains("<!DOCTYPE html>"));
}
Non ottengo un reindirizzamento, probabilmente questo è fatto lato client tramite JavaScript o c'è una logica lato server che valuta le intestazioni HTTP come User-Agent
.
Ma se si verificano reindirizzamenti, è possibile dire a HttpURLConnection di seguirli automaticamente:
conn.setInstanceFollowRedirects(true);
you can get retrieve it by this code
package Test;
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.onvista.de/aktien/snapshot.html?ID_OSI=36714349";
// String urlTest="https://api.twitter.com/oauth/authenticate";
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;
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();
}
}
}