File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes servlet having trouble with POST data Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "servlet having trouble with POST data" Watch "servlet having trouble with POST data" New topic

servlet having trouble with POST data

Ben Wu

Joined: Jan 02, 2002
Posts: 3
I'm having trouble with a servlet that i'm writing that's designed to handle POST data from a java application.
I've managed to get the servlet to recognize GET data using URL("http://localhost:7001/test2?data=foo") calls, but when I tried the following code snippet (pretty much lifted from the java docs)
url = new URL("");
urlConn = url.openConnection();
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
printout = new DataOutputStream (urlConn.getOutputStream());
String content =("param1=" + URLEncoder.encode("foo"));
printout.flush ();
printout.close ();
I get nothing. I tried mapping doPost to doGet, but it appears that the servlet is ignoring the post data.
though i can temporarily get around using GET methods, i'm gonna be hosed when I try to transfer files. any ideas?
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 17280

I believe the proper format for POST is in line format:
The the servlet should be able to read values with getParameter exactly as it does with GET. You might want to check the RFC that defines POST for the finer details.

An IDE is no substitute for an Intelligent Developer.
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13027
As I recall, you also have to use the setRequestMethod("POST") method, otherwise it defaults to a "GET".
When you do an openConnection with a URL that specifies "http" you actually get an instance of the class HttpURLConnection (it extends URLConnection)
There is where you find HTTP specific methods.
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

If you are manually building the GET and POST requests from a GUI app, check out the following for what they look like:

Meng Tan
Ranch Hand

Joined: Jan 20, 2001
Posts: 115
u can try encoding the parameter name as well:
String content =URLEncoder.encode("param1") + "=" + URLEncoder.encode("foo");
I agree. Here's the link:
subject: servlet having trouble with POST data
It's not a secret anymore!