我有一个写入 的旧应用程序,OutputStream
我希望将此流的内容作为文件上传到 Servlet。我已经commons-fileupload
使用 JMeter 测试了 Servlet,它工作得很好。
我会使用 Apache HttpClient,但它需要一个File
而不只是一个输出流。我无法在本地写入文件;如果有一些内存实现File
可能会起作用?
我尝试过使用HttpURLConnection
(如下),但服务器响应“MalformedStreamException:流意外结束”。
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();