Viewing the contents of an http post in Java

I have been experimenting all morning with trying to view an http post (or get) request. (I mean something like this in the case of get)

GET /index.html?userid=joe&password=guessme HTTP/1.1
Host: www.mysite.com
User-Agent: Mozilla/4.0

I tried appending the contents of the input stream to a string buffer, but no love.

Thanks for your help,
Rob

What is it that you’re trying to view? The contents of an HTTP request that was sent somewhere, or the response from the server, or both? And where are you trying to view it from? The client environment, or the HTTP server receiving the request?

I am trying to view the request from the client in a servlet.

Thanks,
Rob

In JSP, you can get the request headers using request.getHeaderNames (returns an array IIRC) and then looping over them and using request.getHeader(headername) to get each header’s value.

I don’t know if there’s a way to view the raw HTTP headers exactly as they come into the server, since they’re parsed before the JSP code gets run.

As for the raw POST data, I haven’t been able to find a way to do it with a bit of Googling. It seems that the Java zombies insist that there is no reason anybody could possibly want to get unparsed POST data, so there’s no method for it in the request object. But I’m no Java expert, so who knows.

I wound up writing a small server that outputs the raw header. Unfortunately, it doesn’t output the POST data, but here it is FWIW:


import java.io.*;
import java.util.*;
import java.net.*;

public class RequestViewer
{
  public static void main(String[] args) throws Exception
  {
    ServerSocket ss = new ServerSocket(Integer.parseInt(args[0]));
    while (true)
    {
      new Thread(new RequestViewerConnection(ss.accept())).start();
    }
  }
}

class RequestViewerConnection implements Runnable
{
  Socket client;
  
  RequestViewerConnection(Socket client) throws SocketException
  {
    this.client = client;
  }

  public void run()
  {
    try
    {
      BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      String line = null;
      while ((line = in.readLine()) != null)
      {
        System.out.print(line);
      }
      client.close();
    }
    catch (IOException e)
    {
      System.out.println("I/O error " + e);
    }
  }
}