Send files directly to WebServices server without a browser, and can send periodic lines

Source: Internet
Author: User

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

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.