Hi there,
I am trying to do a http post to upload a file to my web server using multipart/form-data to a URLConnection for posting. I am using the "MultiPartFormOutputStream".
I am able to reach the url, but it failed to post the request. I've been stuck on this for a while, any help is appreciated! I need to set the name of the content to "Report", see below:
Content-Disposition: form-data; name="Report";
filename="/etc/2007_report.txt"
My code below:
URL url = null;
try {
url = new URL("http://localhost/rsa/upload/report.htm");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Create a boundary string
String boundary = MultiPartFormOutputStream.createBoundary();
// Creating a URL connection
try {
urlConn = MultiPartFormOutputStream.createConnection(url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
urlConn.setRequestProperty("Accept", "*/*");
urlConn.setRequestProperty("Content-Type", MultiPartFormOutputStream
.getContentType(boundary));
// Setting Request Properties
urlConn.setRequestProperty("Connection", "Keep-Alive");
urlConn.setRequestProperty("Cache-Control", "no-cache");
//
urlConn.setRequestProperty("Content-Disposition",
"form-data; name='Report'; filename='/etc/2007_report.txt'");
urlConn.setRequestProperty("Content-Type",
"application/x-test-report");
// Finally ready to create our MultipartFormoutputStream object
MultiPartFormOutputStream out = null;
try {
out = new MultiPartFormOutputStream(urlConn.getOutputStream(),
boundary);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Adding finalFile to Output Stream
try {
out.writeFile("myFile", "text/plain", new File("/etc/2007_report.txt"));
out.close();
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// read response from server
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConn.getInputStream()));
String line = "";
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
System.out.println("File written and closed");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}