URLConnection to upload and download files

The URLConnection class in the java.net package provides developers with the implementation of network communication. It can submit GET and POST requests, upload and download files, and use the wrapper class of IO stream and stream provided by Java to upload multiple files from the bottom. Each parameter set in the upload file is reasonable. The values of these parameters are specified in the HTTP protocol and are determined clearly. In order not to obscure the code, I commented on each line of code.
The main steps of uploading files are as follows:
1. Create URLs and URLConnection objects
2. Set the connection parameters of the URLConnection object, and set the connection parameters without caching.
Set the request attribute Content-Type of the URLConnection object to multipart/form-data
3. Get the output stream from the connection object
4. Get file input stream from disk
6. Write the file content to the output stream of the connection object, each file content is separated by style characters.
7. After all the files are written out, the split string is written in the output stream and the output stream is refreshed.
8. Use input stream to read data from server
9. Close the output input stream and return the result of the server response.

The main steps of downloading files are as follows:
1. Create URLs and URLConnection objects
2. Setting connection parameters for URLConnection objects
3. Get the input stream from the connection object, get the name and length of the file
4. Instantiate the output stream object and use the output stream to write the file data in the input stream into the file object.
5. Close the output input stream and return the file object.

package com.lanshiqin.utils.http;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by Landschin on 2017/4/23.
 * Http Tool class
 */
public class HttpUtil {

    /**
     * Upload files
     *
     * @param actionURL Last destination path address
     * @param filePaths Uploaded File Path Array
     * @return Server response data
     */
    public static String uploadFile(String actionURL, String[] filePaths) {

        String towHyphens = "--";   // Define connection strings
        String boundary = "******"; // Define the delimitation string
        String end = "\r\n";    //Define end newline string
        try {
            // Create URL objects
            URL url = new URL(actionURL);
            // Get the connection object
            URLConnection urlConnection = url.openConnection();
            // Set the input stream allowed to input data to the local machine
            urlConnection.setDoOutput(true);
            // Setting allows output streams to output data to servers
            urlConnection.setDoInput(true);
            // Setting up not to use caching
            urlConnection.setUseCaches(false);
            // Set the content type in the request parameter to be multipart/form-data and the demarcation line of the request content to be ******
            urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            // Getting the output stream from the connection object
            OutputStream outputStream = urlConnection.getOutputStream();
            // Instantiate the data output stream object to input the output stream
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

            // Traversing the length of the file path, writing all the files of the path under the path array to the output stream
            for (int i = 0; i < filePaths.length; i++) {
                // Remove file path
                String filePath = filePaths[i];
                // Get the file name
                String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
                // Write a partitioner to the data output stream
                dataOutputStream.writeBytes(towHyphens + boundary + end);
                // Write the file parameter name and file name to the data output stream
                dataOutputStream.writeBytes("Content-Disposition:form-data;name=file;filename=" + fileName + end);
                // Write the end flag to the data output stream
                dataOutputStream.writeBytes(end);

                // Instantiate file input stream objects, pass file paths in, and read files on disk into memory
                FileInputStream fileInputStream = new FileInputStream(filePath);
                // Define buffer size
                int bufferSize = 1024;
                // Define byte array objects to read buffer data
                byte[] buffer = new byte[bufferSize];
                // Define an integer to store the length of the file currently read
                int length;
                // The loop reads 1024 bytes of data from the file output stream and assigns the length of each read to the length variable until the file is read, with the value of -1 ending the loop.
                while ((length = fileInputStream.read(buffer)) != -1) {
                    // Write data to the data output stream
                    dataOutputStream.write(buffer, 0, length);
                }
                // Each time a complete file stream is written, an end flag is written to the data output stream.
                dataOutputStream.writeBytes(end);
                // Close File Input Stream
                fileInputStream.close();

            }
            // Write a delimiter into the data output stream
            dataOutputStream.writeBytes(towHyphens + boundary + towHyphens + end);
            // Refresh data output stream
            dataOutputStream.flush();

            // Getting byte input stream from connection object
            InputStream inputStream = urlConnection.getInputStream();
            // Instantiate character input stream objects, wrapping byte streams into character streams
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            // Create an input buffer object that passes in the input character stream object
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            // Create a string object to receive each string read from the input buffer
            String line;
            // Create a variable string object to load the final data of the buffer object, and store all the data in the response in the object using string addition
            StringBuilder stringBuilder = new StringBuilder();
            // Read the buffer data line by line using a loop, and assign one line of string data to the line string variable each time until the read behavior space-time identifies the end of the loop.
            while ((line = bufferedReader.readLine()) != null) {
                // Append the data read by the buffer to the variable character object
                stringBuilder.append(line);
            }

            // Close the open input stream in turn
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();

            // Close the open output stream in turn
            dataOutputStream.close();
            outputStream.close();

            // Returns the data that the server responds to
            return stringBuilder.toString();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * Download files
     *
     * @param urlAddress  File url address
     * @param downloadDir Directory of File Preservation
     * @return file
     */
    public static File downloadFile(String urlAddress, String downloadDir) {

        try {
            // Create URL objects
            URL url = new URL(urlAddress);
            // Get the connection object
            URLConnection urlConnection = url.openConnection();
            // Setting allows input streams to enter data locally
            urlConnection.setDoInput(true);
            // Setting to allow output streams to be exported to servers
            urlConnection.setDoOutput(true);
            // Get content length
            int fileLength = urlConnection.getContentLength();
            // Get the file url path name
            String filePathName = urlConnection.getURL().getFile();
            // Get the file name
            String fileName = filePathName.substring(filePathName.lastIndexOf(File.separatorChar) + 1);

            // Define the directory and name of file downloads
            String path = downloadDir + File.separatorChar + fileName;

            // Instantiate file objects
            File file = new File(path);

            // Determine whether the file path exists
            if (!file.getParentFile().exists()) {
                // Create a file if it does not exist
                file.getParentFile().mkdirs();
            }

            // Getting the input byte stream from the connection object
            InputStream inputStream = urlConnection.getInputStream();

            // Instantiate the input stream buffer to stream the input bytes
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

            // Instantiate the output stream object and pass in the file object
            OutputStream outputStream = new FileOutputStream(file);

            // Define an integer to receive the size of the read file
            int size;
            // Define an integer to accumulate the length of the file currently read
            int len = 0;
            // Define byte array objects to load data blocks from the input buffer
            byte[] buf = new byte[1024];
            // Read 1024 bytes of file content from the input buffer to the buf object at one time, and assign the read size to the size variable. When the read is finished, size=-1, and end the cycle reading.
            while ((size = bufferedInputStream.read(buf)) != -1) {
                // Accumulate the size of each read file
                len += size;
                // Write data to the output stream
                outputStream.write(buf, 0, size);
                // Percentage of current file downloads printed
                System.out.println("Download progress:" + len * 100 / fileLength + "%\n");
            }
            // Close the output stream
            outputStream.close();
            // Close the input buffer
            bufferedInputStream.close();
            // Close the input stream
            inputStream.close();

            // Return file object
            return file;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

Keywords: Java network Attribute

Added by jsim on Sat, 06 Jul 2019 22:24:42 +0300