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

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

问题描述

我想上传几个文件到HTTP服务器。基本上我需要的是一些POST请求到服务器几个参数和文件。我见过只上传文件的例子,但没有找到如何传递额外的参数。

这样做的最简单和最自由的解决方案是什么?有没有人有我可以学习的任何文件上传的例子?我一直在Google上搜索几个小时,但是(也许这只是其中的一个)找不到我所需要的。最好的解决方案是不涉及任何第三方类或库的东西。 您通常会使用 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;
文件textFile =新建文件(/ path / to / file.txt);
File binaryFile = new File(/ path / to / file.bin);
String boundary = Long.toHexString(System.currentTimeMillis()); //只产生一些独特的随机值。
字符串CRLF =\r\\\
; // multipart / form-data所需的行分隔符。

URLConnection连接=新的URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty(Content-Type,multipart / form-data; boundary =+ boundary);
$ b $ try(
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output,charset),true);
){
//发送正常的参数。
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();

//发送文本文件。
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); //文本文件本身必须保存在这个字符集中!
writer.append(CRLF).flush();
Files.copy(textFile.toPath(),output);
output.flush(); //在继续写作之前,重要!
writer.append(CRLF).flush(); // CRLF很重要!它表示边界的结束。

//发送二进制文件。
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(); //在继续写作之前,重要!
writer.append(CRLF).flush(); // CRLF很重要!它表示边界的结束。

//多部分/表格数据结束。
writer.append( - + boundary + - )。append(CRLF).flush();
}

//当您需要获取有关响应的信息时,请求会被延迟触发。
int responseCode =((HttpURLConnection)connection).getResponseCode();
System.out.println(responseCode); //应该是200

使用第三方库(如Apache Commons < a href =http://hc.apache.org/ =noreferrer> HttpComponents客户端。



Apache Commons FileUpload ,因为这里有一些错误的建议只对服务器端感兴趣。您不能在客户端使用,也不需要它。



另见




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.

解决方案

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.

Here's a kickoff example:

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

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

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.

See also

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

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