restarting the read after ChangedCharSetException

M

Mike Ditka

I'm trying to use JEditorPane.read(Reader r, Document d) to read a URL.
When it gets a ChangedCharSetException, I getCharSetSpec() and then redefine
the Reader with the charset extracted from CharSetSpec before restarting the
read.

Unfortunately, I still get the same ChangedCharSetException, even with a
reader defined for the correct character set, for example, when trying to
read from www.pons.de, which has "encoding = text/html; charset=iso-8859-1".

What else do I need to do?

Thanks,
MOD

public void showpage(URL url) {
String encoding = null;
while (url != null)
{ Exception eencode = getpage(url, encoding);
if (eencode != null)
{ if (encoding == null && eencode instanceof ChangedCharSetException)
{ encoding =
((ChangedCharSetException)(eencode)).getCharSetSpec().toLowerCase();
System.out.println("encoding = " + encoding);
continue;
}
JOptionPane.showMessageDialog(this, "Invalid URL");
}
break;
}
} catch (Exception ioe) {
ioe.printStackTrace();
JOptionPane.showMessageDialog(this, "Invalid URL");
}
}

Exception getpage(URL url, String encoding) {
Exception urlerror = null;
try {
String protocol = url.getProtocol();
String file = url.getFile();
int q = file.indexOf('?');
if (q <= 0)
q = file.indexOf('#');
if (q > 0)
file = file.substring(0, q);
URL base = new URL(protocol, url.getHost(), url.getPort(), file);
System.out.println("base = " + base);
text.setEditorKit(httpkit);
HTMLDocument doc = new HTMLDocument();
doc.setBase(base);
URLConnection connect = url.openConnection();
if (encoding == null)
encoding = connect.getContentEncoding();
InputStream stream = connect.getInputStream();
InputStreamReader reader;
String charset = null;
if (encoding != null)
{ int keyword = encoding.indexOf("charset=");
if (keyword > 0)
charset = encoding.substring(keyword + 8).trim();
}
System.out.println(encoding + " -> " + charset);
if (charset == null)
reader = new InputStreamReader(stream);
else
reader = new InputStreamReader(stream, charset);
text.read(reader, doc);
} catch (Exception e) {
urlerror = e;
e.printStackTrace();
}
return urlerror;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top