LoginSignup
10

More than 3 years have passed since last update.

posted at

updated at

Java HttpURLConnectionを使ってファイルをアップロードする

以下の記事に実装したサーバーへJavaのクライアントからファイルをアップロードしてみたので、手順を記載する。
Ruby Sinatraサーバーにhttpclientからファイルアップロードしてみた

Rubyと比べても仕方がないが、コードが長くなってしまった。

  • Javaバージョン
    1.8.0_202

コメント欄からご指摘いただきコードを修正しました。

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);
        }
    }
}

なお、本ソースはcurlでファイルアップロードした通信をWiresharkで確認して、javaでも同じような内容になるように作成した。

$ curl -X POST http://localhost:3000/upload -F "file=@./filepath"

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
10