2012-05-06 18 views
6

codifica Im in Java ..ottenere tutte HTML come una stringa da HTMLDocument

Qualcuno sa come posso ottenere il contenuto di un javax.swing.text.html.HTMLDocument come String? Questo è ciò che Ive ha ottenuto finora ...

URL url = new URL("http://www.test.com"); 

HTMLEditorKit kit = new HTMLEditorKit(); 
HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument(); 
doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE); 
Reader HTMLReader = new InputStreamReader(url.openConnection().getInputStream()); 
kit.read(HTMLReader, doc, 0); 

Ho bisogno il contenuto del HTMLDocument come String.

Esempio:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html><head><meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"> 

....... ecc

Tutto l'aiuto sarebbe apprezzato. Ho bisogno di utilizzare classe HTMLDocument in modo che il codice HTML da lavorare correttamente :)

Grazie Daniel

risposta

12
StringWriter writer = new StringWriter(); 
kit.write(writer, doc, 0, doc.getLength()); 
String s = writer.toString(); 
+0

Grazie! Il codice Joop Eggens ha fatto il trucco! – Zelleriation

1

Non è necessario l'editor e il lettore a tutti - basta leggere il flusso di input. Ad esempio, con commons-io IOUtils.toString(inputStream)

oppure è possibile utilizzare:

Content content = document.getContent(); 
String str = content.getString(0, content.length() - 1); 
+0

Questo non funzionerà perché il metodo ereditato [getContent] (http://docs.oracle.com/javase/7/docs/api/javax/swing/text/AbstractDocument.html#getContent%28%29) è protetto . – vallismortis

Problemi correlati