Java writing a POST request

Source: Internet
Author: User

Package Com.mytesting;import Java.io.dataoutputstream;import Java.io.inputstream;import java.net.URL;import Java.net.urlconnection;import Org.apache.commons.io.ioutils;public class Post {public static void main (string[] args) { TODO auto-generated Method Stubdohttppost ("Http://172.18.3.27:8031/Activity/GetActivityList", "{\" tpid\ ": 123}") ;//The first is the request URL the second is the body parameter}/** * Send POST request * * @param postbody * @return */public static string Dohttppost (String Url,strin  G postbody) {//System.out.println ("Originating Data:" + postbody); byte[] XmlData = Postbody.getbytes (); InputStream instr = Null;try {URL url = new url (URL); URLConnection Urlcon = Url.openconnection (); Urlcon.setdooutput (true); Urlcon.setdoinput (true); Urlcon.setusecaches ( FALSE); Urlcon.setrequestproperty ("Content-type", "Application/json"); Urlcon.setrequestproperty ("User-Agent", " App30007/3f845f3287a3c3f20a04b08c5074fc95/2b80541f-1c28-4fe7-8eef-4a20d688a984/0/"); UrlCon.setRequestProperty ( "Content-length", String.valueof (xmldata.length));D AtaoutputStream printout = new DataOutputStream (Urlcon.getoutputstream ());p rintout.write (xmlData);p Rintout.flush (); Printout.close (); instr = Urlcon.getinputstream (); byte[] bis = Ioutils.tobytearray (instr); String responsestring = new string (bis, "UTF-8"); if ((responsestring = = null) | | ("". Equals (Responsestring.trim ()))) {System.out.println ("return null");} SYSTEM.OUT.PRINTLN ("Return data is:" + responsestring); return responsestring;} catch (Exception e) {e.printstacktrace (); return "0";} finally {try {//Out.close (); Instr.close ();} catch (Exception ex) {R Eturn "0";}}}

To introduce the required packages, there are some additional packages that need to be downloaded

Java writing a POST request

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.