My blog has moved! Redirecting...

You should be automatically redirected. If not, visit and update your bookmarks.

Sunday, August 01, 2004

Java Quick Tip of the Day: Reading non-Http Input Into a Servlet

Have you ever wanted to read something other than the results of a get or a post into a servlet? It's not as difficult as you think. It's really just a matter of using the getInputStream() method of the HttpServletRequest object.

Let's take a look at the following example:

public void doPost(HttpServletRequest request,
  HttpServletResponse response)
  throws ServletException, IOException {
 doGet(request, response);
 public void doGet(HttpServletRequest request,
  HttpServletResponse response)
  throws ServletException, IOException {
 BufferedInputStream is = 
   new BufferedInputStream(request.getInputStream());
 InputStreamReader isr = new InputStreamReader(is);
 int character;
 StringBuffer process = new StringBuffer();
 while((character = != -1)
 { process.append((char)character);

Looking at the code, notice that the first thing we're doing is calling the doGet() method from the doPost() method. We do this as a simple way to redirect all incoming data to the same code. We then create a BufferedInputStream object is from the request.getInputStream() method. From is we've created an InputStreamReader object isr in order to read the inputstream. Next we create a StringBuffer object process and fill it with the characters we read from the inputstream...for those of you who've used inputstreams this code should look very familar. Finally we do something with process.

Why would you ever want to do this? One example of of using this technique is when you want to turn a servlet into a webservice. I'm currently working on a how-to article on this subject. Look for it shortly.

Technorati search