通常,你会
java.net.URLConnection用来触发HTTP请求。通常,你还可以
multipart/form-data对混合的POST内容(二进制和字符数据)使用编码。单击链接,其中包含信息以及如何组成
multipart/form-data请求正文的示例。该规范在RFC2388中有更详细的描述。
这是一个启动示例:
String url = "http://example.com/upload";String charset = "UTF-8";String param = "value";File textFile = new File("/path/to/file.txt");File binaryFile = new File("/path/to/file.bin");String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.String CRLF = "rn"; // Line separator required by multipart/form-data.URLConnection connection = new URL(url).openConnection();connection.setDoOutput(true);connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);try ( OutputStream output = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);) { // Send normal param. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name="param"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); writer.append(CRLF).append(param).append(CRLF).flush(); // Send text file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name="textFile"; filename="" + textFile.getName() + """).append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset! writer.append(CRLF).flush(); Files.copy(textFile.toPath(), output); output.flush(); // important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. // Send binary file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name="binaryFile"; filename="" + binaryFile.getName() + """).append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); Files.copy(binaryFile.toPath(), output); output.flush(); // important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF).flush();}// Request is lazily fired whenever you need to obtain information about response.int responseCode = ((HttpURLConnection) connection).getResponseCode();System.out.println(responseCode); // Should be 200当你使用诸如
Apache Commons HttpComponentsClient之类的第三方库时,此代码不太冗长。
某些错误建议表明,
Apache Commons FileUpload仅在服务器端有用。你不能在客户端使用它,也不需要它。



