Website lesen

royal7

Grünschnabel
Hi,

ich habe ein großes Problem!
Ich habe gerade erst mit Java begonnen und ich möchte den Sourcecode einer Website in einer Datei oder einer Variable speichern. Leider habe ich keinen Schimmer
wie man das anstellen könnte, könnt ihr mir vielleicht helfen?

Danke im Voraus,
Patrick:p
 
Über Google oder hier im Forum hättest du das bestimmt gefunden.

Code:
try {
  URL url = new URL("http://www.google.com");
  URLConnection connection = url.openConnection();
  InputStream is = connection.getInputStream();
  BufferedReader reader = new BufferedReader(new InputStreamReader(is));
  // ..
} catch (MalformedURLException ex) {
  ex.printStackTrace();
} catch (IOException ex) {
  ex.printStackTrace();
}

oder...
Code:
try {
  String hostname = "www.google.com";
  final Socket sock = new Socket(hostname, 80);
  PrintWriter writer = new PrintWriter(sock.getOutputStream(), true);
  final BufferedReader reader = new BufferedReader(
    new InputStreamReader(sock.getInputStream()));
 
  (new Thread() {
    public void run() {
      try {
        String line;
        while (!sock.isClosed() && (line = reader.readLine()) != null)
          System.out.println(line);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }).start();
 
  writer.println("GET / HTTP/1.1");
  writer.println("Host: "+hostname);
  writer.println();
} catch (UnknownHostException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

Das mit dem Dateischreiben überlasse ich mal dir. Das findest du schnell raus ;)
 
Danke für die schnelle Antwort!
Mit Threats hab ich nich nichts gemacht werd mich aber gleich ein bisschen spielen
 
Ich bins nochmal:

ich hab mich jetzt ein bisschen gespielt, hat auch alles funktioniert, bis ich versucht habe mich über einen Socket mit einer IP zu verbinden:

//**********
InetAddress addr = InetAddress.getByAddress(new byte[]{(byte)209,(byte)85,(byte)229,(byte)106});
Socket sock = new Socket(addr, 80);
PrintWriter writer = new PrintWriter(sock.getOutputStream(), true);
final BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));

for(i=0;i<=10;i++){
System.out.println(reader.readLine());
}
writer.close();
reader.close();
//**********


das Programm hängt bei: "System.out.println(reader.readLine());"
es kommt auch kein Error aber ich weiß nicht wieso
Wisst ihr vielleicht was falsch ist?
 
Was kommt denn genau für ein Error?

Edit:
Zusätzlich würde ich die Scheife umändern. um den Fehler zu vermeiden, dass du keine 11 Zeilen hast.
(Ich denke du willst bestimmt 10 Zeilen haben, aber da müsste es i<10 heißen)

old:
Java:
for(i=0;i<=10;i++){
System.out.println(reader.readLine());
}

new:
Java:
int counter = 0;
String zeile = null;
while((zeile = reader.readLine()) != null && counter <= 10) {
     System.out.println(zeile);
     counter++;
}
 
Zuletzt bearbeitet:
Es kommt eben kein Error
deine Version funktioniert auch nicht, ich bins auch schon mit dem Debugger Zeile für Zeile durchgegangen, aber er bleibt einfach bei:

System.out.println(reader.readLine());

hängen.
 
Ich habe nicht gemeint, dass meine Funkion deinen Fehler behebt, ich wollte lediglich sagen, dass du sonst einen Fehler bekommen könntest, wenn deine Webseite nicht so viele Zeilen hat, wie deine Schleife durchläuft.

Und mti dem Error hatte ich mich verlesen :(
 
Achso^^, das hab ich schon nachgeschaut.
Ich hab das Programm jetzt ~5min lang laufen lassen ohne dass sich was tut, aber danach ist 10x das Wort "null" als Ausgabe gekommen.
 
Ich kann nur vermuten wo das Problem liegt. Ich denke es liegt ansich nciht an deiner Logik sondern an der Funktionsweise von readLine(); . Soweit ich weiß wartet diese Methode auf ein Ende sprich \n oder \r - irgendsowas in der Art. Wenn er das nicht findet, kann er natürlich keine Zeile einlesen und bleibt hängen. Also würde ich eher versuch einmal nur eine bestimmte Anzahl an Zeichen einzulesen.

--Java docs--
Code:
read
public int read()
         throws IOExceptionRead a single character. 

Overrides:
read in class Reader
Returns:
The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached 
Throws: 
IOException - If an I/O error occurs

--------------------------------------------------------------------------------

read
public int read(char[] cbuf,
                int off,
                int len)
         throws IOExceptionRead characters into a portion of an array. 
This method implements the general contract of the corresponding read method of the Reader class. As an additional convenience, it attempts to read as many characters as possible by repeatedly invoking the read method of the underlying stream. This iterated read continues until one of the following conditions becomes true: 

The specified number of characters have been read, 
The read method of the underlying stream returns -1, indicating end-of-file, or 
The ready method of the underlying stream returns false, indicating that further input requests would block. 
If the first read on the underlying stream returns -1 to indicate end-of-file then this method returns -1. Otherwise this method returns the number of characters actually read. 
Subclasses of this class are encouraged, but not required, to attempt to read as many characters as possible in the same fashion. 

Ordinarily this method takes characters from this stream's character buffer, filling it from the underlying stream as necessary. If, however, the buffer is empty, the mark is not valid, and the requested length is at least as large as the buffer, then this method will read characters directly from the underlying stream into the given array. Thus redundant BufferedReaders will not copy data unnecessarily. 


Specified by:
read in class Reader
Parameters:
cbuf - Destination buffer
off - Offset at which to start storing characters
len - Maximum number of characters to read 
Returns:
The number of characters read, or -1 if the end of the stream has been reached 
Throws: 
IOException - If an I/O error occurs
 
Zuletzt bearbeitet:
ich hab mich jetzt ein bisschen gespielt, hat auch alles funktioniert, bis ich versucht habe mich über einen Socket mit einer IP zu verbinden:

//**********
...
Socket sock = new Socket(addr, 80);
// (*)
PrintWriter writer = new PrintWriter(sock.getOutputStream(), true);
...
//**********

Um Dich wirklich mit der Socket zu verbinden, fehlt hier (*) IMHO doch wohl noch das connect - etwa in dieser Form:
Code:
socket.connect( addr, SOCKETTIMEOUT );

Gruß
Klaus
 

Neue Beiträge

Zurück