Java tips: Java sends a POST request to a web site

Source: Internet
Author: User

Sending a POST request to a web site only takes a few simple steps:

First, you need to talk to urlconnection under the URL. Urlconnection can be easily obtained from the URL. For example:

// Using java.net. url and

// Java.net. urlconnection

URL url = new

URL ("http://jobsearch.dice.com/jobsearch/jobsearch.cgi ");

Urlconnection connection = URL. openconnection ();

Set the connection to the output mode. Urlconnection is usually used as input, such as downloading a Web page. By setting urlconnection as output, you can transmit data to your web page. The following describes how to do this:

...

Connection. setdooutput (true );

Finally, to get the outputstream, put it in the writer and put it into the post information, for example:

...

Outputstreamwriter out = newoutputstreamwriter (UC. getoutputstream (), "8859_1 ");

Out. Write ("username = Bob & Password =" + password + "");

// Remember to clean up

Out. Flush ();

Out. Close ();

In this way, you can send a post that looks like this:

Post/Jobsearch. cgi HTTP 1.0

Accept: text/plain

Content-Type: Application/X-WWW-form-urlencoded

Content-Length: 99

Username = Bob

Password = someword

Once the message is sent successfully, use the following method to obtain the server response:

Connection. getinputstream ();

Some websites use post instead of get, because post can carry more data without URLs, which makes it look not so huge. Using the rough Code listed above, Java code can easily communicate with these sites.

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.