【发布时间】:2016-06-29 00:23:41
【问题描述】:
我正在使用 HttpURLConnection 通过 post 方法发送文件。我正在向文件发送一个“student_id”参数。在每个发布请求中发送一个文件时,该代码工作正常。 但是,我如何更新下面的代码以在一个帖子请求中发送多个文件,其中所有文件都属于同一个“student_id”?
try{
File textFile2 = new File("info.txt");
URL url = new URL("htttp://wwww.students.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setChunkedStreamingMode(0);
urlConnection.setDoOutput(true);
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream output = urlConnection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"student_id\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF).append("25").append(CRLF).flush();
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"newfile\"; filename=\"" + textFile2.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(textFile2.toPath(), output);//copies all bytes in a file to the output stream
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush();
writer.append("--" + boundary + "--").append(CRLF).flush();
InputStream responseStream;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
我尝试在“newfile”中使用参数添加“multiple”,但它不起作用
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"newfile\" multiple; filename=\"" + textFile2.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(textFile2.toPath(), output);//copies all bytes in a file to the output stream
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush();
writer.append("--" + boundary + "--").append(CRLF).flush();
【问题讨论】:
-
将 OutputStream 的包装器与对原始 OutputStream 的直接写入混合在一起会产生问题。使用 PrintStream 而不是 PrintWriter,并将该 PrintStream 传递给 Files.copy。一旦将 OutputStream 包装在 PrintStream 或 OutputStreamWriter 之类的东西中,就不应再次引用该 OutputStream。
-
如果可能的话,你能给我举个例子来说明你的建议吗
-
将
PrintWriter writer = …更改为PrintStream writer = new PrintStream(output, true, charset);。将 Files.copy 语句更改为Files.copy(textFile2.toPath(), writer);。这样,所有行都写入完全相同的输出对象。删除对 output.flush() 的调用。记得打电话给writer.close()。
标签: java file post httpurlconnection