从 Java 客户端上传文件到 HTTP 服务器 [英] Upload files from Java client to a HTTP server

查看:51
本文介绍了从 Java 客户端上传文件到 HTTP 服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一些文件上传到 HTTP 服务器.基本上我需要的是某种带有一些参数和文件的服务器的 POST 请求.我看过只上传文件的例子,但没有找到如何传递额外的参数.

I'd like to upload a few files to a HTTP server. Basically what I need is some sort of a POST request to the server with a few parameters and the files. I've seen examples of just uploading files, but didn't find how to also pass additional parameters.

这样做的最简单和免费的解决方案是什么?有没有人有任何我可以研究的文件上传示例?我已经用谷歌搜索了几个小时,但是(也许只是那些日子之一)找不到我需要的东西.最好的解决方案是不涉及任何第三方类或库.

What's the simplest and free solution of doing this? Does anyone have any file upload examples that I could study? I've been googling for a few hours, but (maybe it's just one of those days) couldn't find exactly what I needed. The best solution would be something that doesn't involve any third party classes or libraries.

推荐答案

您通常会使用 java.net.URLConnection 来触发 HTTP 请求.您通常还可以使用 multipart/form-data 混合 POST 内容(二进制和字符数据)的编码.单击该链接,它包含有关如何编写 multipart/form-data 请求正文的信息和示例.该规范在 RFC2388 中有更详细的描述.

You'd normally use java.net.URLConnection to fire HTTP requests. You'd also normally use multipart/form-data encoding for mixed POST content (binary and character data). Click the link, it contains information and an example how to compose a multipart/form-data request body. The specification is in more detail described in 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 = "
"; // 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 等 3rd 方库时,此代码不那么冗长.

This code is less verbose when you use a 3rd party library like Apache Commons HttpComponents Client.

Apache Commons FileUpload 一些人错误地建议这里只对服务器端感兴趣.您不能在客户端使用也不需要它.

The Apache Commons FileUpload as some incorrectly suggest here is only of interest in the server side. You can't use and don't need it at the client side.

这篇关于从 Java 客户端上传文件到 HTTP 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆