私はHttpURLConnectionを使ってpostメソッドでファイルを送信しています。私はファイルと共に 'student_id'というパラメータを送信しています。各投稿要求で1つのファイルを送信するとき、コードは正常に動作しています。 しかし、どのようにすべてのファイルが同じ 'student_id'に属している1つの投稿要求で複数のファイルを送信するために、以下のコードを更新できますか?1つの投稿に複数のファイルを送信するJAXのHttpURLConnectionのリクエスト
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」でパラメータを指定して「複数」を追加しようとしましたが、それは
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のラッパーを混在させると、問題が発生することがあります。 PrintWriterの代わりにPrintStreamを使用し、そのPrintStreamをFiles.copyに渡します。 OutputStreamをPrintStreamやOutputStreamWriterのようにラップしたら、そのOutputStreamを再び参照しないでください。 – VGR
可能であれば、あなたが提案しているものの例を教えてください。 – ryh12
'PrintWriter writer = ...'を 'PrintStream writer = new PrintStream(output、true、charset);に変更してください。 Files.copy文を 'Files.copy(textFile2.toPath()、writer);に変更してください。そうすれば、すべての行がまったく同じ出力オブジェクトに書き込まれます。 output.flush()への呼び出しを削除します。 'writer.close()'を呼び出すことを忘れないでください。 – VGR