将文件从Java客户端上传到HTTP服务器

我想将一些文件上传到HTTP服务器。基本上,我需要的是对服务器的某种POST请求,其中包含一些参数和文件。我看到了仅上传文件的示例,但没有找到如何也传递其他参数的示例。

什么是最简单,免费的解决方案?有人有我可以学习的文件上传示例吗?我已经搜寻了几个小时,但是(也许只是那几天)找不到我真正需要的东西。最好的解决方案是不涉及任何第三方类或库的东西。

回答:

通常,你会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 = "\r\n"; // 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 HttpComponents Client之类的第三方库时,此代码不太冗长。

某些错误建议表明,Apache Commons FileUpload仅在服务器端有用。你不能在客户端使用它,也不需要它。

以上是 将文件从Java客户端上传到HTTP服务器 的全部内容, 来源链接: utcz.com/qa/428471.html

回到顶部