Simulate an http post request using a Java program

Source: Internet
Author: User

In Web applications, http post requests are generally sent through pages, but Java programs can also be used to simulate page sending requests. The Code is as follows:
Import Java. io. bufferedreader; <br/> Import Java. io. ioexception; <br/> Import Java. io. inputstream; <br/> Import Java. io. inputstreamreader; <br/> Import Java. io. outputstreamwriter; <br/> Import java.net. URL; <br/> Import java.net. urlconnection; <br/> public class testpost {<br/> Public static void testpost () throws ioexception {<br/>/** <br/> * first, you must talk to urlconnection in the URL. Urlconnection can be easily obtained from the URL. For example: // using <br/> * java.net. URL and // java.net. urlconnection <br/> * normal process for sending a request using the page: Enter the user name and password in http://www.faircanton.com/message/loginlytebox.asp, and log on to the system, <br/> * Go To http://www.faircanton.com/message/check.aspfor <br/> * return the verification result to another page <br/> * process of sending a request using a Java program: use urlconnection to send a request to http://www.faircanton.com/message/check.asp< br/> * and pass two parameters: user name and password <br/> * and then use the program to obtain the verification result <br/> */<br/> URL url = new URL ("http://www.faircanton.com/message/check.asp"); <br/> urlconnection connection = URL. openconnection (); <br/>/** <br/> * then set the connection to the output mode. Urlconnection is usually used as input, such as downloading a Web page. <Br/> * by setting urlconnection as output, you can transmit data to your web page. The following describes how to: <br/> */<br/> connection. setdooutput (true); <br/>/** <br/> * Finally, to get outputstream, constrain it to writer and put it into post information for simplicity, example :... <br/> */<br/> outputstreamwriter out = new outputstreamwriter (connection. getoutputstream (), "8859_1"); <br/> out. write ("username = Kevin & Password = **********"); // transmits data to the page. The key to post! <Br/> // remember to clean up <br/> out. flush (); <br/> out. close (); <br/>/** <br/> * to send a post that looks like this: <br/> * post/Jobsearch. cgi HTTP 1.0 accept: <br/> * text/plain Content-Type: Application/X-WWW-form-urlencoded <br/> * Content-Length: 99 username = Bob Password = someword <br/> */<br/> // once the message is sent successfully, you can obtain the server response using the following method: <br/> string scurrentline; <br/> string stotalstring; <br/> scurrentl INE = ""; <br/> stotalstring = ""; <br/> inputstream l_urlstream; <br/> l_urlstream = connection. getinputstream (); <br/> // The legendary Three-tier package! <Br/> bufferedreader l_reader = new bufferedreader (New inputstreamreader (<br/> l_urlstream); <br/> while (scurrentline = l_reader.readline ())! = NULL) {<br/> stotalstring + = scurrentline + "/R/N"; </P> <p >}< br/> system. out. println (stotalstring); <br/>}</P> <p> Public static void main (string [] ARGs) throws ioexception {<br/> testpost (); <br/>}< br/>}

I have passed this test.

If you want to upload files in addition to post some data, you can use one of the following two functions:
/** <Br/> * send a file to the specified network address through HTTP. <Br/> * @ Param Params parameters to be transferred during transmission <br/> * @ Param filename the local location of the file to be transferred. <Br/> * @ throws transferexception <br/> */<br/> Public String dopost (hashmap Params, inputstream Stream) <br/> throws transferexception <br/> {<br/> urlconnection conn = NULL; // URL link object. <Br/> bufferedreader in = NULL; // read object of the returned information after the request. <Br/> string keyname = NULL; <br/> try <br/> {<br/> conn = URL. openconnection (); <br/> Conn. setusecaches (false); <br/> Conn. setdooutput (true); <br/> Conn. setrequestproperty ("Content-Type", "multipart/form-Data"); </P> <p> // set the parameter <br/> If (Params! = NULL) <br/>{< br/> set Keys = Params. keyset (); <br/> // retrieve the parameter name and value through the parameter set <br/> If (! Keys. isempty () <br/>{< br/> iterator = keys. iterator (); <br/> while (iterator. hasnext () <br/>{< br/> keyname = (string) iterator. next (); <br/> // Add parameters to the connection object <br/> Conn. addrequestproperty (<br/> keyname, <br/> (string) Params. get (keyname )); <br/>}< br/> // construct the transmission file <br/> // fileinputstream FD = new fileinputstream (filename ); <br/> bufferedinputstream Bis = new bufferedin Putstream (Stream); <br/> bytearrayoutputstream baos = new bytearrayoutputstream (); <br/> int ch; <br/> while (CH = bis. Read ())! =-1) <br/> baos. write (CH); <br/> byte [] filedata = baos. tobytearray (); </P> <p> // transfers a file. <Br/> dataoutputstream dos = <br/> New dataoutputstream (<br/> New bufferedoutputstream (Conn. getoutputstream (); <br/> dos. write (filedata); <br/> dos. flush (); <br/> dos. close (); </P> <p> In = <br/> New bufferedreader (<br/> New inputstreamreader (Conn. getinputstream (); <br/> // In. close (); <br/>}< br/> catch (filenotfoundexception Fe) <br/>{< br/> inputstream err = (httpurlconnection) Conn ). gete Rrorstream (); <br/> If (ERR = NULL) <br/> throw new transferexception ("Unknown error occurred during network transmission "); <br/> In = new bufferedreader (New inputstreamreader (ERR); <br/>}< br/> catch (ioexception IOE) <br/>{< br/> IOE. printstacktrace (); <br/> throw new transferexception ("Network Transmission Error! "); <Br/>}</P> <p> // return the message <br/> stringbuffer response = new stringbuffer (); <br/> string line; <br/> try <br/> {<br/> while (line = in. readline ())! = NULL) <br/> response. append (LINE + "/N"); <br/> in. close (); <br/>}< br/> catch (ioexception IOE) <br/>{< br/> IOE. getstacktrace (); <br/> throw new transferexception ("network response error! "); <Br/>}< br/> return response. tostring (); <br/>}</P> <p>/** <br/> * send files to the specified network address through HTTP. <Br/> * @ Param Params parameters to be transmitted during transmission <br/> * @ Param data content to be transmitted. <Br/> * @ throws transferexception <br/> */<br/> Public inputstream dopost (hashmap Params, byte [] data) <br/> throws transferexception <br/> {<br/> urlconnection conn = NULL; // URL link object. <Br/> bufferedreader in = NULL; // read object of the returned information after the request. <Br/> string keyname = NULL; <br/> try <br/> {<br/> conn = URL. openconnection (); <br/> Conn. setusecaches (false); <br/> Conn. setdooutput (true); <br/> Conn. setrequestproperty ("Content-Type", "multipart/form-Data"); </P> <p> // set the parameter <br/> If (Params! = NULL) <br/>{< br/> set Keys = Params. keyset (); <br/> // retrieve the parameter name and value through the parameter set <br/> If (! Keys. isempty () <br/>{< br/> iterator = keys. iterator (); <br/> while (iterator. hasnext () <br/>{< br/> keyname = (string) iterator. next (); <br/> // Add parameters to the connection object <br/> Conn. addrequestproperty (<br/> keyname, <br/> (string) Params. get (keyname); <br/>}</P> <p> // transfer a file. <Br/> dataoutputstream dos = <br/> New dataoutputstream (<br/> New bufferedoutputstream (Conn. getoutputstream (); <br/> dos. write (data); <br/> dos. flush (); <br/> dos. close (); <br/> return Conn. getinputstream (); <br/>}< br/> catch (filenotfoundexception Fe) <br/>{< br/> inputstream err = (httpurlconnection) Conn ). geterrorstream (); <br/> If (ERR = NULL) <br/> throw new transferexception ("occurs during network transmission Unknown error "); <br/> else <br/> throw new transferexception (" Unknown error "); <br/>}< br/> catch (ioexception IOE) <br/>{< br/> IOE. printstacktrace (); <br/> throw new transferexception ("Network Transmission Error! "); <Br/>}< br/>}

These two functions are written by employees of the company and have not been tested using actual examples.

We can also use the htmlparse jar package (this package and related documents can be downloaded at http://htmlparser.sourceforge.net/here) to parse the obtained HTML.
Example:
Import org.html parser. node; <br/> Import org.html parser. nodefilter; <br/> Import org.html parser. parser; <br/> Import org.html parser. filters. tagnamefilter; <br/> Import org.html parser. tags. tabletag; <br/> Import org.html parser. util. nodelist; <br/> public class testhtmlparser {<br/> Public static void testhtml () {<br/> try {<br/> string scurrentline; <br/> string stotalstring; <br/> scurrentline = ""; <br /> Stotalstring = ""; <br/> JAVA. io. inputstream l_urlstream; <br/> java.net. URL l_url = new java.net. URL ("http://www.ideagrace.com/html/doc/2006/07/04/00929.html"); <br/> java.net. httpurlconnection l_connection = (java.net. httpurlconnection) l_url.openconnection (); <br/> l_connection.connect (); <br/> l_urlstream = l_connection.getinputstream (); <br/> JAVA. io. bufferedreader l_reader = new Java. io. Bufferedreader (New java. Io. inputstreamreader (l_urlstream); <br/> while (scurrentline = l_reader.readline ())! = NULL) {<br/> stotalstring + = scurrentline + "/R/N"; <br/> // system. out. println (stotalstring); <br/>}< br/> string testtext = extracttext (stotalstring); <br/> system. out. println (testtext); </P> <p >}catch (exception e) {<br/> E. printstacktrace (); <br/>}</P> <p> Public static string extracttext (string inputhtml) throws exception {<br/> stringbuffer text = new stringbuffer (); <br/> parser = parser. createparser (new string (inputhtml. getbytes (), "GBK"), "GBK"); <br/> // traverse all nodes <br/> nodelist nodes = parser. extractallnodesthatmatch (New nodefilter () {<br/> Public Boolean accept (node) {<br/> return true; <br/>}< br/> }); </P> <p> system. out. println (nodes. size (); // number of print nodes <br/> for (INT I = 0; I <nodes. size (); I ++) {<br/> node nodet = nodes. elementat (I); <br/> // system. out. println (nodet. gettext (); <br/> text. append (new string (nodet. toplaintextstring (). getbytes ("GBK") + "/R/N"); <br/>}< br/> return text. tostring (); <br/>}</P> <p> Public static void test5 (string resource) throws exception {<br/> parser myparser = new Parser (Resource ); <br/> myparser. setencoding ("GBK"); <br/> string filterstr = "table"; <br/> nodefilter filter = new tagnamefilter (filterstr); <br/> nodelist = myparser. extractallnodesthatmatch (filter); <br/> tabletag = (tabletag) nodelist. elementat (11); </P> <p >}</P> <p> Public static void main (string [] ARGs) throws exception {<br/> // test5 ("http://www.ggdig.com"); <br/> testhtml (); <br/>}< br/>}

This example has passed the test.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.