Stream Both Character and Binary Data via a Servlet
Writing a servlet that can perform character streaming is easy, but streaming binary content is trickier. This simple six-step tutorial guides you through a streaming solution that enables you to stream both character and binary data.
by Raj Behera
April 1, 2003
very programmer can quite easily write a servlet that can perform character streaming of XML or HTML data. As long as the proper MIME type is set before the data is streamed, the process is pretty simple (response.setContentType("text/xml"); sets XML content, while response.setContentType("text/html"); sets HTML).
The following code provides an example of streamCharacterData(), the method for character streaming:
/*
* This Method handles streaming Character data
* <p>
* @param String urlstr ex: http://localhost/test.pdf etc.
* @param String format ex: xml or HTML etc.
* @param PrintWriter outstr
* @param HttpServletResponse resp
*/
private void streamCharacterData(String urlstr,String format, PrintWriter outstr, HttpServletResponse resp)
{
String ErrorStr = null;
try{
//find the right MIME type and set it as contenttype
resp.setContentType(getMimeType(format));
InputStream in = null;
try{
URL url = new URL(urlstr);
URLConnection urlc= url.openConnection();
int length = urlc.getContentLength();
in = urlc.getInputStream();
resp.setContentLength(length);
int ch;
while ( (ch = in.read()) != -1 ) {
outstr.print( (char)ch );
}
} catch (Exception e) {
e.printStackTrace();
ErrorStr = "Error Streaming the Data";
outstr.print(ErrorStr);
} finally {
if( in != null ) {
in.close();
}
if( outstr != null ) {
outstr.flush();
outstr.close();
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
It's quick, easy and you get access to all the articles on DevX.
This registration/login is to allow you to read articles on devx.com. Already a member?
To become a member of DevX.com create your Member Profile by completing the form below. Membership is free!