Java Simulation form Upload form
View the HTTP request submitted by the form form
ImportJava.io.*;Importjava.net.*; Public classFileUpload {/*** Simulate form form, upload file in the form of output stream to write the file to the URL, and then use the input stream to get the response of the URL *@paramURL request address form form URL address *@paramfilePath file on server save path *@returnThe response information of the String URL returns the value *@throwsIOException*/ Publicstring send (string URL, string filePath)throwsIOException {String result=NULL; File File=NewFile (FilePath); if(!file.exists () | | |File.isfile ()) { Throw NewIOException ("File does not exist"); } /*** First Part*/URL urlobj=Newurl (URL); //ConnectionHttpURLConnection con =(HttpURLConnection) urlobj.openconnection (); /*** Set Key values*/Con.setrequestmethod ("POST");//Request MethodCon.setdoinput (true); Con.setdooutput (true);//when it is post, you need to set it because you want to enter the data streamCon.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//files that need to be submittedStringBuilder SB =NewStringBuilder (); Sb.append ("--" +boundary+ "\ r \ n"); Sb.append ("Content-disposition:form-data;name=\" file\ "filename=\" "+ file.getname () +" \ "\" \ "\ \"); 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 ()); //Output Table HeaderOut.write (head); //file Body part//push the file into the URL in the same way that it was streamedDataInputStream in =NewDataInputStream (Newfileinputstream (file)); intbytes = 0; byte[] Bufferout =New byte[1024]; while((bytes = In.read (bufferout))! =-1) {out.write (bufferout,0, bytes); } in.close (); //common form data that needs to be submittedSB =NewStringBuilder (); Sb.append ("\r\n--" +boundary+ "\ r \ n"); Sb.append ("Content-disposition:form-data;name=\" type\ "\r\n\r\n");//Note: There is a line between setting the data header and the data contentSb.append ("1\r\n"); Sb.append ("--" +boundary+ "\ r \ n"); Sb.append ("Content-disposition:form-data;name=\" wxroleid\ "\r\n\r\n"); Sb.append ("201\r\n"); Head= Sb.tostring (). GetBytes ("Utf-8"); Out.write (head); //End Part byte[] foot = ("--" + Boundary + "--\r\n"). GetBytes ("Utf-8");//define the last data separator lineout.write (foot); Out.flush (); Out.close (); StringBuffer Buffer=NewStringBuffer (); BufferedReader Reader=NULL; Try { //defines the response of the BufferedReader input stream to read the URLReader =NewBufferedReader (NewInputStreamReader (Con.getinputstream ())); String Line=NULL; while(line = Reader.readline ())! =NULL) { //System.out.println (line);Buffer.append (line); } if(result==NULL) {result=buffer.tostring (); } } Catch(IOException e) {System.out.println ("Send POST request exception!" " +e); E.printstacktrace (); Throw NewIOException ("Data Read exception"); } finally { if(reader!=NULL) {reader.close (); } } returnresult; } //Test Using Public Static voidMain (string[] args)throwsIOException {String FilePath= "File path to upload";//As D:/test.pdf String sendurl= "Http://192.168.0.125:8080/dataProvider/uploadReport"; String result=NULL; FileUpload FileUpload=NewFileUpload (); Result=fileupload.send (Sendurl, FilePath); SYSTEM.OUT.PRINTLN (result); }}
At the time of testing, if an HTTP 400 error occurs, it is that the format of the Imitation form form is not correct and the relevant information cannot be resolved. The wrong place is usually in (note line breaks and blank lines):
Java simulation form upload data