Write Data to post request in Java
The most common purpose of http post requests is to send form parameters to the server. In addition to sending form data, you can also use the post message body to send various types of data (such as plain text and XML documents ). This article describes how to use Java to write data to the body of the POST request.
Import Java. io. ioexception; import Java. io. inputstream; import Java. io. outputstreamwriter; import java.net. URL; import java.net. urlconnection; import Java. util. logging. level; import Java. util. logging. logger; import Org. apache. commons. io. ioutils; public class requesttest {public static void main (string [] ARGs) {try {// configure and open a connection to the site you will send the requesturl url = new URL ("http://www.iana.org/domains/example/"); urlconnection = URL. openconnection (); // set the dooutput attribute to true to write data into urlconnection. setdooutput (true); // defines the content type of the data to be written. We set it to application/X-WWW-form-urlencoded type urlconnection. setrequestproperty ("Content-Type", "application/X-WWW-form-urlencoded"); // get the output stream object outputstreamwriter out = new outputstreamwriter (urlconnection. getoutputstream (); // write data to the requested bodyout. write ("message = Hello World chszs"); out. flush (); out. close (); // read the response from the server inputstream = urlconnection. getinputstream (); string encoding = urlconnection. getcontentencoding (); string body = ioutils. tostring (inputstream, encoding); system. out. println (body);} catch (ioexception e) {logger. getlogger (requesttest. class. getname ()). log (level. severe, null, e );}}}
Is it easy?