Java - Upload OutputStream as HTTP File Upload

淺唱寂寞╮ 提交于 2019-12-07 14:28:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!