Upload a file using Java HttpURLConnection

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

Upload a file using Java HttpURLConnection
[Java] Create a temporary file
Make a rhombus using Java
Run a batch file from Java
Create a Java project using Eclipse
Let's create a file upload system using Azure Computer Vision API and Azure Storage Java SDK
Why does Java call a file a class?
[Personal memo] Writing a file using BufferedWriter
[Java] Test S3 upload / download using "S3 ninja"
Reading a file using Java's Scanner class
[Personal memo] Reading a file using BufferedReader
[java] HttpURLConnection POST
java file creation
[Java] Creating an Excel file using Apache POI
Read a string in a PDF file with Java
Write to a file using ShiftJIS-Read a file (Kotlin / JVM)
A story about trying to operate JAVA File
A bat file that uses Java in windows
Ssh connect using SSHJ from a Java 6 app
[Java] Let's create a mod for Minecraft 1.14.4 [0. Basic file]
Create a portfolio app using Java and Spring Boot
[Java] File system operation
Sorting using java comparator
Create a Java development environment using jenv on Mac
How to jump from Eclipse Java to a SQL file
Read Java Property file
java (split source file)
java core: chopped core file
[Java] Let's create a mod for Minecraft 1.16.1 [Basic file]
java build a triangle
Scraping practice using Java ②
I tried using Log4j2 on a Java EE server
I tried OCR processing a PDF file with Java
Using the database (SQL Server 2014) from a Java program 2018/01/04
Scraping practice using Java ①
How to convert A to a and a to A using AND and OR in Java
How to convert a file to a byte array in Java
Try to build a Java development environment using Docker
Java11: Run Java code in a single file as is
I tried scraping a stock chart using Java (Jsoup)
[Beginner] android app that rolls a ball using a sensor [Java]
Activate Excel file A1 cell of each sheet in Java
Try Hello World using plain Java on a Docker container
Socket communication with a web browser using Java and JavaScript ②
About the behavior when doing a file map with java
Socket communication with a web browser using Java and JavaScript ①
Create a MOB using the Minecraft Java Mythicmobs plugin | Preparation 1
A Simple CRUD Sample Using Java Servlet / JSP and MySQL
I tried OCR processing a PDF file with Java part2
I made a Dockerfile to start Glassfish 5 using Oracle Java
Try using RocksDB in Java
Try scraping using java [Notes]
Creating a calendar using Ruby
iOS: File upload with SFTP
Create a java method [Memo] [java11]
What is a jar file?
File upload with Spring Boot
Find a subset in Java
What is a Java collection?
[Java] Make it a constant
Create a fortune using Ruby