Write Data to post request in Java

Source: Internet
Author: User

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?

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.