How to post ByteArrayOutputStream via http

余生颓废 提交于 2019-12-25 07:46:42

问题


I am currently reading a file from then writing it to an HTTP connection which saves the file locally to disk - it's working fine.

However, because of the environment I'm working within I cannot read files from disk, rather they are pulled from a database and stored in a ByteArrayOutputStream in my java code.

So instead of starting by reading a file from disk, I need to use a ByteOutputArrayStream and write that to an http connection instead.

I need an efficient method to do this - If I can modify my current code (bloew) that's fine - I'm willing to scrap it all if necessary...

        // This is the primary call from jsp
        public String postServer(String[] args)throws Exception{
            System.out.println("******* HTTPTestJPO  inside postServer");

            String requestURL = "http://MyServer:8080/TransferTest/UploadServlet";
            String charset = "UTF-8";
            String sTest=args[0];
            String sResponse="";

            System.out.println("******* HTTPTestJPO incoming file string sTest:"+sTest);

            MultipartUtility multipart = new MultipartUtility(requestURL, charset);
            StringTokenizer inFiles=new StringTokenizer(sTest,",");
            while(inFiles.hasMoreTokens()){
                String tmpFileName=inFiles.nextToken();
                System.out.println("*******  tokenized tmpFileName:"+tmpFileName);
                File uploadFile1 = new File(tmpFileName);
                try {
                    multipart.addFilePart("fileUpload", uploadFile1);
                } catch (IOException ex) {
                    System.err.println("******* HTTPTestJPO  EXCEPTION: "+ex);
                }
            }

            sResponse = multipart.handleFinish();
            System.out.println("******* HTTPTestJPO   SERVER REPLIED:"+sResponse);
            return sResponse;
        }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Multipart utility
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /**
         * This utility class provides an abstraction layer for sending multipart HTTP
         * POST requests to a web server.
         * @author www.codejava.net
         *
         */
        public class MultipartUtility {
            private final String boundary;
            private static final String LINE_FEED = "\r\n";
            private HttpURLConnection httpConn;
            private String charset;
            private OutputStream outputStream;
            private PrintWriter writer;

            /**
             * This constructor initializes a new HTTP POST request with content type
             * is set to multipart/form-data
             * @param requestURL
             * @param charset
             * @throws IOException
             */
            public MultipartUtility(String requestURL, String charset)throws IOException {
                this.charset = charset;

                // creates a unique boundary based on time stamp
                boundary = "===" + System.currentTimeMillis() + "===";

                URL url = new URL(requestURL);
                httpConn = (HttpURLConnection) url.openConnection();
                httpConn.setUseCaches(false);
                httpConn.setDoOutput(true); // indicates POST method
                httpConn.setDoInput(true);
                httpConn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
                //httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
                //httpConn.setRequestProperty("Test", "Bonjour");
                outputStream = httpConn.getOutputStream();
                writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),true);
            }

            /**
             * Adds a upload file section to the request
             * @param fieldName name attribute in <input type="file" name="..." />
             * @param uploadFile a File to be uploaded
             * @throws IOException
             */

            public void addFilePart(String fieldName, File uploadFile)throws IOException {
                String fileName = uploadFile.getName();
                writer.append("--" + boundary).append(LINE_FEED);
                writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(LINE_FEED);
                writer.append("Content-Type: "+ URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
                writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
                writer.append(LINE_FEED);
                writer.flush();

   // HOW CAN I MODIFY THIS TO SEND AN EXISTING BYTEARRAYOUTPUTSTREAM INSTEAD OF A DISK FILE??
                FileInputStream inputStream = new FileInputStream(uploadFile);
                byte[] buffer = new byte[4096];
                int bytesRead = -1;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
                inputStream.close();

                writer.append(LINE_FEED);
                writer.flush();     
            }

            /**
             * Completes the request and receives response from the server.
             * @return a list of Strings as response in case the server returned
             * status OK, otherwise an exception is thrown.
             * @throws IOException
             */
            private String handleFinish() throws IOException {
                String sResponse = "";

                //close out the multipart send
                writer.append(LINE_FEED).flush();
                writer.append("--" + boundary + "--").append(LINE_FEED);
                writer.close();

                // checks server's status code first
                int status = httpConn.getResponseCode();
                sResponse=Integer.toString(status);
                System.out.println("******* HTTPTestJPO http response code:"+status);
                // if (status == HttpURLConnection.HTTP_OK) {
                    // BufferedReader reader = new BufferedReader(new InputStreamReader(
                            // httpConn.getInputStream()));
                    // String line = reader.readLine();
                    // while ((line = reader.readLine()) != null) {
                        // sResponse+=line;
                    // }
                    // reader.close();
                     httpConn.disconnect();
                // } else {
                    // throw new IOException("Server returned non-OK status: " + status);
                // }

                return sResponse;
            }
        }
    }

回答1:


The contents of a ByteArrayOutputStream can be written to another OutputStream using the writeTo method, like this:

byteArrayOutputStream.writeTo(outputStream);

Another option would be to create a new InputStream:

InputStream inputStream = new ByteArrayInputStream(
        byteArrayOutputStream.toByteArray());

but calling toByteArray makes a copy of the byte array, so is more expensive.



来源:https://stackoverflow.com/questions/42909244/how-to-post-bytearrayoutputstream-via-http

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