Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Emulating a HTTP POST

Status
Not open for further replies.

BillyKrow

Programmer
Aug 27, 2001
67
US
I need to emulate a HTTP post with direct Java code. I'm doing doing something like this:

URL url = new URL("HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);

Writer writer = new OutputStreamWriter(conn.getOutputStream());
writer.write("test");
writer.flush();

I never hit the doPost method in the target servlet even though I get no errors. I'm guessing I need to encode what I'm writing to properly post but am unsure how. I've done some research on the REST architecture which is along the lines of what I'm trying to do but can't find simple examples that don't require 3rd party software.
 
You are missing a connect() call, a stream close() call, and a disconnect() call.

Eg :

Code:
                                String url = "[URL unfurl="true"]http://www.google.com";[/URL]

                                HttpURLConnection c = (HttpURLConnection)(new URL(url).openConnection());
                                c.setRequestProperty("Connection","Keep-Alive");
                                c.setRequestMethod("GET");
                                c.setUseCaches(false);
                                c.connect();
                                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                                String line = "";
                                while ((line = br.readLine()) != null) {
                                        System.out.print(line +"\n");
                                }

                                br.close();
                                c.disconnect();

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top