I tried uploading a file from a Java client to the server implemented in the following article, so I will describe the procedure. I tried uploading a file from httpclient to the Ruby Sinatra server
It can't be helped compared to Ruby, but the code has become longer.
I have corrected the code by pointing out from the comment section. </ font>
Uploader.java
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
public class Uploader {
private static final String EOL = "\r\n";
public static int Send(String filename, String url, String method) throws IOException {
try (FileInputStream file = new FileInputStream(filename)) {
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
final String boundary = UUID.randomUUID().toString();
con.setDoOutput(true);
con.setRequestMethod(method);
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (OutputStream out = con.getOutputStream()) {
out.write(("--" + boundary + EOL +
"Content-Disposition: form-data; name=\"file\"; " +
"filename=\"" + filename + "\"" + EOL +
"Content-Type: application/octet-stream" + EOL + EOL)
.getBytes(StandardCharsets.UTF_8)
);
byte[] buffer = new byte[128];
int size = -1;
while (-1 != (size = file.read(buffer))) {
out.write(buffer, 0, size);
}
out.write((EOL + "--" + boundary + "--" + EOL).getBytes(StandardCharsets.UTF_8));
out.flush();
System.err.println(con.getResponseMessage());
return con.getResponseCode();
} finally {
con.disconnect();
}
}
}
public static void main(String[] args) throws IOException {
if (args.length < 2) {
System.err.println("Input [Upload file path] [Upload URL]");
return;
}
String filename = args[0];
String url = args[1];
int res = Uploader.Send(filename, url, "POST");
if (res == HttpURLConnection.HTTP_OK) {
System.err.println("Success!");
} else {
System.err.printf("Failed %d\n", res);
}
}
}
In addition, this source was created so that the communication that uploaded the file with curl was confirmed with Wireshark and the contents were the same in java.
$ curl -X POST http://localhost:3000/upload -F "file=@./filepath"
Recommended Posts