3

I wrote the following simple groovy code that handles a request.

if (init)
  data = ""

if (line.size() > 0) {
  data += "--> " + line + "\n"
} else {
  println "HTTP/1.1 200 OK\n"
  println data
  println "----\n"
  return "success"
}

I then run it by doing groovy -l 8888 ServerTest.groovy However, it doesn't seem to print any POST data. I am testing it by doing curl -d "d=test" http://localhost:8888/ Does anybody know how to get that data in groovy?

Amir Raminfar
  • 33,777
  • 7
  • 93
  • 123

1 Answers1

2

In order for the port listening option to work, you have to also use the -n or -p options.

Example:

// test.groovy
println "Got $line from socket"

$ groovy -n -l8888 test.groovy &
groovy is listening on port 8888
$ echo hello | nc localhost 8888
Got hello from socket
$

EDIT: Also, note that you are getting a single line from a socket, not a complete HTTP request. So in the case of a GET, you're going to get multiple lines to process for each request, looking something like this:

GET / HTTP/1.1
Host: localhost:8888
[a variable number of headers]

The whole request is terminated by a blank line. With a POST, it'll look something like this:

POST / HTTP/1.1
Host: localhost:8888
[a variable number of headers]

d=test

The request is the same, except after the blank line that terminates the GET, is the POST data. Unfortunately, the POST data is not terminated with a newline, and groovy is using line buffered input, so it just sits there waiting for a newline.

However, you can force it to proceed by closing your end of the socket. Try something like this:

System.err.println(line) // log the incoming data to the console

if (line.size() == 0) {
    println "HTTP/1.1 200 OK\r\n\r\nhello"
    socket.shutdownOutput()
}

Then groovy will flush the buffer and finish closing other end, and you'll have your POST data.

ataylor
  • 64,891
  • 24
  • 161
  • 189
  • That's not my question. I need to be able to get the body of the post content. Not using GET. – Amir Raminfar Jan 03 '11 at 01:35
  • OK, I think I understand the problem. Edited my response. – ataylor Jan 03 '11 at 17:22
  • where do do I put socket.shutdownOutput()? I tried putting it in my else but doesn't seem to work – Amir Raminfar Jan 05 '11 at 21:00
  • The socket should be shutdown after you you've received a blank line as input, after you've sent all the output. In your example, you return "success" to groovy, which closes the socket completely and loses the last buffered line. You need to let groovy pass you one last line after the shutdown. – ataylor Jan 05 '11 at 22:10
  • I think I tried what you said but the POST value is still not printed. Maybe you post the working script. Thanks – Amir Raminfar Jan 07 '11 at 00:10