Tuesday, July 28, 2009

How to make a post request in java?

I want to make a post request in java. Say a page1 has form which requires a post request to let you go a different page. How can I do that in java?


Just to explain a bit more, say I want to acess a password protected page. Now I need to make apost request to do that right. How do I do that.

How to make a post request in java?
// create a URL object


URL url = new URL(loginPage);





// open the conncetion


HttpURLConnection connection = (HttpURLConnection)url.openConnection();





// Let the run-time system (RTS) know that we want input.


connection.setDoInput(true);


// Let the RTS know that we want to do output


connection.setDoOutput(true);


// No caching, we want the real thing


connection.setUseCaches(false);


// set the content type property


connection.setRequestProperty("Content... "application/x-www-form-urlencoded");


// set the user agent property


connection.setRequestProperty("User-ag... agent);


// set request method


connection.setRequestMethod("POST");


// follow redirections


connection.setInstanceFollowRedirects(...





// create the post body to send


String content = "post body";


DataOutputStream printout = new DataOutputStream ( connection.getOutputStream () );





// send the data


printout.writeBytes(content);


printout.flush();


printout.close();





// get the response


BufferedReader input = new BufferedReader ( new InputStreamReader(connection.getInputStr... );

brandon flowers

No comments:

Post a Comment