10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-04-26

以下の記事に実装したサーバーへ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"
10
11
9

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
  3. You can use dark theme
What you can do with signing up
10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?