How can I make a multipart/form-data POST request using Java?

后端 未结 11 1472
攒了一身酷
攒了一身酷 2020-11-22 05:56

In the days of version 3.x of Apache Commons HttpClient, making a multipart/form-data POST request was possible (an example from 2004). Unfortunately this is no longer possi

11条回答
  •  粉色の甜心
    2020-11-22 06:22

    Here's a solution that does not require any libraries.

    This routine transmits every file in the directory d:/data/mpf10 to urlToConnect

    
    String boundary = Long.toHexString(System.currentTimeMillis());
    URLConnection connection = new URL(urlToConnect).openConnection();
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    PrintWriter writer = null;
    try {
        writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
        File dir = new File("d:/data/mpf10");
        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                continue;
            }
            writer.println("--" + boundary);
            writer.println("Content-Disposition: form-data; name=\"" + file.getName() + "\"; filename=\"" + file.getName() + "\"");
            writer.println("Content-Type: text/plain; charset=UTF-8");
            writer.println();
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
                for (String line; (line = reader.readLine()) != null;) {
                    writer.println(line);
                }
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
        }
        writer.println("--" + boundary + "--");
    } finally {
        if (writer != null) writer.close();
    }
    // Connection is lazily executed whenever you request any status.
    int responseCode = ((HttpURLConnection) connection).getResponseCode();
    // Handle response
    

提交回复
热议问题