http - Submit HTML form data using Java to retrieve a download from a jsp application -
i have obscure issue. in process of porting perl java , 1 of methods in perl code posts jsp app , downloads zip file. working part of perl code follows appears using retrieve file.
$mech->get ( $url ); $mech->submit_form( fields => { upload => variable1, selectvalue => variable2, }, );
the jsp page follows:
<!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>extract features</title> </head> <body> <form action="extract.zip" method="post" enctype="multipart/form-data"> <table> <tr> <th align="left">file:</th> <td><input type="file" name="upload"></td> </tr> <tr> <th align="left">code:</th> <td><select name="selectvalue"> <option value="13" selected="selected">13</option> <option value="14">14</option> <option value="15">15</option> </select></td> </tr> <tr> <td align="center" colspan="2"><input type="submit" value="submit"></td> </tr> </table> </form> </body> </html>
and java code using try access it:
url url = new url(s.geturlscheme(), s.geturlhost(), s.geturlfile()); string urlparameters = "upload=c:\\testfile.txt&selectvalue=14"; httpurlconnection connection = (httpurlconnection)url.openconnection(); connection.setdoinput(true); connection.setdooutput(true); connection.setinstancefollowredirects(false); connection.setrequestmethod("post"); connection.setrequestproperty("content-type", "text/html"); connection.setrequestproperty("charset", "iso-8859-1"); connection.setrequestproperty("content-length", integer.tostring(urlparameters.length())); connection.setusecaches(false); dataoutputstream wr = new dataoutputstream(connection.getoutputstream()); wr.writebytes(urlparameters); wr.flush(); wr.close(); inputstream = connection.getinputstream(); outputstream os = new fileoutputstream(".\\test.html"); int data; while ((data=is.read()) != -1) { os.write(data); } is.close(); os.close(); connection.disconnect();
first of sorry example have posted in comment. thought trying perform simple post
request submitting values. have missed uploading file. since uploading file (note don't pass filename here) mutlipart request (you see in jsp: enctype="multipart/form-data"
) , has little more work programmatically.
when submitting multipart form request looks this:
-----------------------------253171262814565 content-disposition: form-data; name="myfile"; filename="test.bin" content-type: application/octet-stream test data -----------------------------253171262814565 content-disposition: form-data; name="submit" submit -----------------------------253171262814565--
that strange alphanumerics called boundary (are chosen randomly browser) , used distringuish between submitted fields (files or normal fields). in above example submitted fields were:
- a field named "myfile"
<input type="file">
in form. user selected file namedtest.bin
. file data single text linetest data
- a normal field value of
"submit"
of<input type="submit">
button
below have copied code an example @ code.java.net provides class can in creating such requests.
please modify hard-coded urls , files match case. have not tried out should give idea of how create request above one. (note there 2 classes: 1 constructs request , 1 main()
method test it)
side note: change of line character \r\n
not depend on system part of how multipart requests constructed. should use no matter if system windows or linux
i hope helps
package net.codejava.networking; import java.io.bufferedreader; import java.io.file; import java.io.fileinputstream; import java.io.ioexception; import java.io.inputstreamreader; import java.io.outputstream; import java.io.outputstreamwriter; import java.io.printwriter; import java.net.httpurlconnection; import java.net.url; import java.net.urlconnection; import java.util.arraylist; import java.util.list; /** * utility class provides abstraction layer sending multipart http * post requests web server. * @author www.codejava.net * */ public class multipartutility { private final string boundary; private static final string line_feed = "\r\n"; private httpurlconnection httpconn; private string charset; private outputstream outputstream; private printwriter writer; /** * constructor initializes new http post request content type * set multipart/form-data * @param requesturl * @param charset * @throws ioexception */ public multipartutility(string requesturl, string charset) throws ioexception { this.charset = charset; // creates unique boundary based on time stamp boundary = "===" + system.currenttimemillis() + "==="; url url = new url(requesturl); httpconn = (httpurlconnection) url.openconnection(); httpconn.setdooutput(true); // indicates post method httpconn.setdoinput(true); httpconn.setrequestproperty("content-type", "multipart/form-data; boundary=" + boundary); outputstream = httpconn.getoutputstream(); writer = new printwriter(new outputstreamwriter(outputstream, charset), true); } /** * adds form field request * @param name field name * @param value field value */ public void addformfield(string name, string value) { writer.append("--" + boundary).append(line_feed); writer.append("content-disposition: form-data; name=\"" + name + "\"") .append(line_feed); writer.append("content-type: text/plain; charset=" + charset).append( line_feed); writer.append(line_feed); writer.append(value).append(line_feed); writer.flush(); } /** * adds upload file section request * @param fieldname name attribute in <input type="file" name="..." /> * @param uploadfile file uploaded * @throws ioexception */ public void addfilepart(string fieldname, file uploadfile) throws ioexception { string filename = uploadfile.getname(); writer.append("--" + boundary).append(line_feed); writer.append( "content-disposition: form-data; name=\"" + fieldname + "\"; filename=\"" + filename + "\"") .append(line_feed); writer.append( "content-type: " + urlconnection.guesscontenttypefromname(filename)) .append(line_feed); writer.append("content-transfer-encoding: binary").append(line_feed); writer.append(line_feed); writer.flush(); fileinputstream inputstream = new fileinputstream(uploadfile); byte[] buffer = new byte[4096]; int bytesread = -1; while ((bytesread = inputstream.read(buffer)) != -1) { outputstream.write(buffer, 0, bytesread); } outputstream.flush(); inputstream.close(); writer.append(line_feed); writer.flush(); } /** * completes request , receives response server. * @return list of strings response in case server returned * status ok, otherwise exception thrown. * @throws ioexception */ public list<string> finish() throws ioexception { list<string> response = new arraylist<string>(); writer.append(line_feed).flush(); writer.append("--" + boundary + "--").append(line_feed); writer.close(); // checks server's status code first int status = httpconn.getresponsecode(); if (status == httpurlconnection.http_ok) { bufferedreader reader = new bufferedreader(new inputstreamreader( httpconn.getinputstream())); string line = null; while ((line = reader.readline()) != null) { response.add(line); } reader.close(); httpconn.disconnect(); } else { throw new ioexception("server returned non-ok status: " + status); } return response; } } //--------------------------------------------------------- package net.codejava.networking; import java.io.file; import java.io.ioexception; import java.util.list; /** * program demonstrates usage of multipartutility class. * @author www.codejava.net * */ public class multipartfileuploader { public static void main(string[] args) { string charset = "utf-8"; file uploadfile1 = new file("e:/test/pic1.jpg"); file uploadfile2 = new file("e:/test/pic2.jpg"); string requesturl = "http://localhost:8080/fileuploadspringmvc/uploadfile.do"; try { multipartutility multipart = new multipartutility(requesturl, charset); multipart.addformfield("description", "cool pix"); multipart.addfilepart("fileupload", uploadfile1); multipart.addfilepart("fileupload", uploadfile2); list<string> response = multipart.finish(); system.out.println("server replied:"); (string line : response) { system.out.println(line); } } catch (ioexception ex) { system.out.println("error: " + ex.getmessage()); ex.printstacktrace(); } } }
Comments
Post a Comment