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