为什么在 java 中发送 multipart/form-data 中的文件时我们必须同时使用 Writer 和 OutputStream?

Why does when sending a file in multipart/form-data in java we have to use both a Writer and a OutputStream?

您好,我在 java 中看到过许多用于在 multipart/form-data 中发送文件的示例代码。 但是他们同时使用了 Writer 和 OutputStream。 为什么他们不能只使用其中之一?

这是他们发送的示例代码

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

public class MainClass_External2 {
    public static void main(String[] args){
        try{
            // Connect to the web server endpoint
            URL serverUrl =
                new URL("http://posttestserver.com/post.php?dir=example");
            HttpURLConnection urlConnection = (HttpURLConnection)serverUrl.openConnection();

            String boundaryString = "----SomeRandomText";
            String fileUrl = "abc.txt";
            File logFileToUpload = new File(fileUrl);

// Indicate that we want to write to the HTTP request body
            urlConnection.setDoOutput(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.addRequestProperty("Content-Type","multipart/form-data; boundary=" + boundaryString);

// Indicate that we want to write some data as the HTTP request body
            urlConnection.setDoOutput(true);

            OutputStream outputStreamToRequestBody = urlConnection.getOutputStream();
            BufferedWriter httpRequestBodyWriter =
                new BufferedWriter(new OutputStreamWriter(outputStreamToRequestBody));

// Include value from the myFileDescription text area in the post data
            httpRequestBodyWriter.write("\n\n--" + boundaryString + "\n");
            httpRequestBodyWriter.write("Content-Disposition: form-data; name=\"myFileDescription\"");
            httpRequestBodyWriter.write("\n\n");
            httpRequestBodyWriter.write("Log file for 20150208");

// Include the section to describe the file
            httpRequestBodyWriter.write("\n--" + boundaryString + "\n");
            httpRequestBodyWriter.write("Content-Disposition: form-data;"
                    + "name=\"myFile\";"
                    + "filename=\""+ logFileToUpload.getName() +"\""
                    + "\nContent-Type: text/plain\n\n");
            httpRequestBodyWriter.flush();

// Write the actual file contents
            FileInputStream inputStreamToLogFile = new FileInputStream(logFileToUpload);

            int bytesRead;
            byte[] dataBuffer = new byte[1024];
            while((bytesRead = inputStreamToLogFile.read(dataBuffer)) != -1){
                outputStreamToRequestBody.write(dataBuffer, 0, bytesRead);
            }

// Mark the end of the multipart http request
            httpRequestBodyWriter.write("\n--" + boundaryString + "--\n");
            httpRequestBodyWriter.flush();

// Close the streams
            outputStreamToRequestBody.close();
            httpRequestBodyWriter.close();

            // Read response from web server, which will trigger the multipart HTTP request to be sent.
            BufferedReader httpResponseReader =
                    new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String lineRead;
            while((lineRead = httpResponseReader.readLine()) != null) {
                System.out.println(lineRead);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

基本上,响应包含文本和二进制数据,因此同时使用 WriterOutputStream 非常有意义。

writer只是对输出流进行包装,用于写入文本。输出流本身用于写入二进制数据。

Why can't they use just use one of them?

仅使用 OutputStream 会使编写文本更加痛苦。当需要写入二进制数据时,仅使用 Writer 是不合适的。