Java analog POST request sends binary data

Source: Internet
Author: User

When it comes to data communication between programs, we sometimes need to customize the binary format and then interact with binary data over HTTP. The sample code for the interaction is as follows:

 Public Static voidMain (string[] args) {String result= ""; Try{String URL= "Http://localhost:8080/Demo/SiteApi"; URL Realurl=Newurl (URL); //opening and linking between URLsURLConnection conn =realurl.openconnection (); //to set common request propertiesConn.setrequestproperty ("Accept", "*/*"); Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("User-agent", "mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) "); Conn.setrequestproperty ("Content-type", "Application/octet-stream"); //to send a POST request, you must set the following two linesConn.setdooutput (true); Conn.setdoinput (true); //Send Request ParametersDataOutputStream dos=NewDataOutputStream (Conn.getoutputstream ()); String content= "I love China";                        Dos.write (Content.getbytes ()); //buffer for flush output streamDos.flush (); //defines the response of the BufferedReader input stream to read the URLBufferedReader in =NewBufferedReader (NewInputStreamReader (Conn.getinputstream ()));        String Line;  while(line = In.readline ())! =NULL) {result+=Line ; } System.out.println (result);//Print Output Results}Catch(Exception e) {System.out.println ("Exception," +e.getmessage ());    E.printstacktrace (); }}

Let's talk about the point:
1. Set the value of Content-type must be application/octet-stream, refer to http://tool.oschina.net/commons/
2. Sending binary data must be used to DataOutputStream

Java analog POST request sends binary data

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.