Package Com.toic.test;import java.io.datainputstream;import java.io.dataoutputstream;import java.io.File; Import Java.io.fileinputstream;import Java.io.ioexception;import Java.io.outputstream;import Java.net.httpurlconnection;import Java.net.url;import Java.util.date;import Java.util.timer;import Java.util.TimerTask; Public classFileUpload {/** * Send Request * * @param url* Request address * @param filepath* file path * @return * @throws IOException*/ Publicsynchronized string Send (string URL, String filePath) throws IOException {file file=NewFile (filePath);if(!file.exists () | | |File.isfile ()) {return "ERROR";}/** * Part I.*/URL urlobj=Newurl (URL); HttpURLConnection Con=(HttpURLConnection) urlobj.openconnection ();/** * Set key values*/Con.setrequestmethod ("POST");//Submit form as post, default get modeCon.setdoinput (true); Con.setdooutput (true); Con.setusecaches (false);//Post mode cannot use cache//Set Request header informationCon.setrequestproperty ("Connection","keep-alive"); Con.setrequestproperty ("Charset","UTF-8");//Set BoundariesString boundary ="----------"+System.currenttimemillis (); Con.setrequestproperty ("Content-type","multipart/form-data; boundary="+boundary);//Request body Information//The first part:StringBuilder SB =NewStringBuilder (); Sb.append ("--");// ////////you have to have two more lines .sb.append (boundary); Sb.append ("\ r \ n"); Sb.append ("content-disposition:form-data;name=\ "file\"; filename=\ ""+ file.getname () +"\ "\ r \ n"); Sb.append ("content-type:application/octet-stream\r\n\r\n");byte[] head = Sb.tostring (). GetBytes ("Utf-8");//get the output streamOutputStream out=NewDataOutputStream (Con.getoutputstream ()); out. Write (head);//file Body partDataInputStreaminch=NewDataInputStream (Newfileinputstream (file));intbytes =0;byte[] Bufferout =New byte[1024x768]; while((bytes =inch. Read (bufferout))! =-1) { out. Write (Bufferout,0, bytes);}inch. Close ();//End Partbyte[] foot = ("\r\n--"+ Boundary +"--\r\n"). GetBytes ("Utf-8");//define the last data separator line out. Write (foot); out. Flush (); out. Close ();/** * Read server response, must read, otherwise commit unsuccessful*/return "Upload |"+ FilePath +" | "+ Con.getresponsecode () +" | "+con.getresponsemessage ();/** * The following method of reading is also possible*///try {// //defines the response of the BufferedReader input stream to read the URL//BufferedReader reader = new BufferedReader (New InputStreamReader (//Con.getinputstream ()));//String line = null;//While (line = Reader.readline ()) = null) {//System.out.println (line);// }//} catch (Exception e) {//System.out.println ("Send POST request exception!") "+ e);//e.printstacktrace ();// } }Static intCounter=0;//periodic upload know to reach specified conditions Public voidtimevoid () {Final timer timer=NewTimer (); TimerTask TT=NewTimerTask () {@Override Public voidrun () {FileUpload up=NewFileUpload (); intj=1; while(j<Ten){ Try{System. out. println (Up.send ("Http://127.0.0.1:7001/RESTfull001/file/upload", "C:\\Documents and Settings\\yanxxx\\my documents\\my pictures\\copy ("+(Ten*COUNTER+J) +") of Xz.jpg" ) ); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } J++; } counter++; System. out. println ("Counter--->"+counter); if(counter==3) {timer.cancel (); System. out. println ("It's the point ! "); } } }; //Execute TT Delay 10s to execute 1 times per minuteTimer.schedule (TT,10000,1* -* +/2);}//perform t.schedule (TT, DT, 60*1000) in the specified time period; Execute once per minute Public voidAttimeschedule () {Date dt=NewDate (); DT=NewDate (Dt.getyear (), Dt.getmonth (), Dt.getday (), dt.gethours (), Dt.getminutes (), -) ; Timer T=NewTimer (false); TimerTask TT=NewTimerTask () {@Override Public voidrun () {//where to put the taskSystem. out. println ("exectue Time:"+NewDate ()); }}; T.schedule (TT, DT, -* +); //t.scheduleatfixedrate (TT, N, 60*1000);//with fixed execution frequency//t.scheduleatfixedrate (TT, DT, 60*1000);//with fixed execution frequency } Public Static voidMain (string[] args) throws IOException {//send files directly to WebServices server without a browser, and can send periodic linesFileUpload ttask=NewFileUpload (); //ttask.timevoid ();Ttask.attimeschedule (); }}
Send files directly to WebServices server without a browser, and can send periodic lines