问题
I've got a legacy application that writes to an OutputStream
, and I'd like to have the contents of this stream uploaded as a file to a Servlet. I've tested the Servlet, which uses commons-fileupload
, using JMeter and it works just fine.
I would use Apache HttpClient, but it requires a File
rather than just an output stream. I can't write a file locally; if there was some in-memory implementation of File
perhaps that might work?
I've tried using HttpURLConnection
(below) but the server responds with "MalformedStreamException: Stream ended unexpectedly".
URL url = new URL("http", "localhost", 8080, "/upload");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
String boundary = "---------------------------7d226f700d0";
connection.setRequestProperty("Content-Disposition", "form-data; name=\"file\"");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestMethod("POST");
connection.setChunkedStreamingMode(0);
connection.connect();
OutputStream out = connection.getOutputStream();
byte[] boundaryBytes =("--" + boundary + "\r\n").getBytes();
out.write(boundaryBytes);
//App writes to outputstream here
out.write("\r\n".getBytes());
out.write(("--"+boundary+"--").getBytes());
out.write("\r\n".getBytes());
out.flush();
out.close();
connection.disconnect();
回答1:
The PostMethod allows you to set a RequestEntity, which is an interface which you can implement. you just need to implement the RequestEntity.writeRequest
method appropriately.
Or, if you want HttpClient to handle the multi-part stuff for you, you could use MultipartRequestEntity with a custom Part.
来源:https://stackoverflow.com/questions/12623532/java-upload-outputstream-as-http-file-upload