Java-将OutputStream上载为HTTP文件上载 [英] Java - Upload OutputStream as HTTP File Upload
问题描述
我有一个写到OutputStream
的旧应用程序,我想将此流的内容作为文件上传到Servlet.我已经使用JMeter测试了使用commons-fileupload
的Servlet,并且工作正常.
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.
我将使用Apache HttpClient,但它需要一个File
而不只是一个输出流.我不能在本地写文件;如果有File
在内存中的实现,也许可行?
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?
我尝试使用HttpURLConnection
(如下),但是服务器响应"MalformedStreamException:流意外结束".
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();
推荐答案
PostMethod允许您设置一个RequestEntity,它是您可以实现的接口.您只需要适当地实现RequestEntity.writeRequest
方法即可.
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.
或者,如果您希望HttpClient为您处理多部分内容,则可以将MultipartRequestEntity与自定义部分一起使用.
Or, if you want HttpClient to handle the multi-part stuff for you, you could use MultipartRequestEntity with a custom Part.
这篇关于Java-将OutputStream上载为HTTP文件上载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!