--#--
Follow the Bounce
--#--
The lazy man's solution to figuring out how to send
IIS the POST request it expects is just to see what
Netscape or Internet Explorer sends.
To do that, I adapted some code from David Flanagan's Java Examples in a Nutshell
book.
Flanagan's code, called HttpMirror, only handles GET
requests. As GETs always end with an empty line, as soon as
HttpMirror reads and empty line it breaks and fetches the
request (if it can). I've modified the code to keep on reading a
past empty lines. This presents a problem -- when to stop
reading a request.
The solution, of course, is to do just what servers in the real
world do -- it reads the "Content-length: " line in the request
header and, once past the first empty line, reads those many bytes
and no more.
Basically, this code binds itself to a specific port and listens
for requests. When a socket opens, it spawns a client reads the
bytes off the socket and sends them right back from whence they
came.
ServerSocket ss = new ServerSocket(port);
for(;;) {
Socket client = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
out.println("HTTP/1.0 200 ");
out.println("Content-Type: text/plain");
out.println();
String line;
int cLen = 0;
while ((line = in.readLine()) != null) {
out.println(line);
if (line.indexOf("ength: ") >= 0) {
cLen = Bounce.getContentLen(line);
}
if (line.length() == 0) break;
}
if (cLen > 0) {
char[] buffer = new char[cLen];
in.read(buffer, 0, cLen);
line = new String(buffer);
out.println(line);
}
out.flush();
out.close();
in.close();
client.close();
}
Note that this code checks for a Length: header line,
and if it finds it, calculates the length of the POST using
a built-in static function:
static int getContentLen(String line) throws NumberFormatException {
String l = line.substring(line.indexOf(": ") + 2 );
return (Integer.parseInt(l));
}
We need to wrap the whole thing in a try ... catch to handle any
problems that arise in reading the POST or sending data back to
the client. But, putting it all together, we get this
code.
Now, we just need to Bounce Netscape's POST off our server.