Ottenere un errore del server interno 500 nell'API di discourse durante il tentativo di caricare un file in Java

Sto usando l’API di Discourse per caricare un’immagine. Ecco il codice Java che uso per caricare il file

import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.*;
import java.io.*;

public class Upload {
  private final static String BASE_URL = "http://localhost:4200";
  private final static String API_KEY = "958543d9f5d4df2c2739b8f9156cbd18759d192d435fb4d2c08e5f61fdf3b699";
  static String boundary = "WebKitFormBoundary7MA4YWxkTrZu0gW";

private static final String LINE_FEED = "\r\n";

	public static void main(String[] args) {
    try {
		URL url = new URL(BASE_URL + "/uploads.json");
		HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
		httpConn.setRequestMethod("POST");
    httpConn.setDoOutput(true);
		httpConn.setRequestProperty("api-key", API_KEY);
		httpConn.setRequestProperty("api-username", "devarshmavani19");
		httpConn.setRequestProperty("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
		OutputStream outputStream = new DataOutputStream(System.out);//httpConn.getOutputStream();
		PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream));
		addFormField("type", "image", writer);
		addFormField("synchronous", "true", writer);
		addFilePart("file", new File("/home/devarsh/Desktop/small.jpeg"), "", writer, outputStream);
    String response = finish(writer, httpConn, outputStream);
    System.out.println(response);
    }
    catch(Exception e ) {e.printStackTrace();}
	}

	public static void addFormField(String name, String value, PrintWriter writer) {
      writer.append("----" + boundary).append(LINE_FEED);
      writer.append("Content-Disposition: form-data; name=" + name + "")
      .append(LINE_FEED);

      writer.append("Content-Type: text/plain; charset=US-ASCII").append(
        LINE_FEED);
      writer.append(LINE_FEED);
      writer.append(value).append(LINE_FEED);
      writer.flush();
  }

  public static void addFilePart(String fieldName, File file, String name, PrintWriter writer, OutputStream outputStream)
    throws IOException {
    writer.append("----" + boundary).append(LINE_FEED);
    writer.append(
    "Content-Disposition: form-data; name=" + fieldName
    + "; filename=" + file.getName() + "")
    .append(LINE_FEED);
    writer.append(
                "Content-Type: "
                        + URLConnection.guessContentTypeFromName(file.getName()))
                .append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

		FileInputStream inputStream = new FileInputStream(file);
    byte[] buffer = new byte[4096];
		int bytesRead;
		while ((bytesRead = inputStream.read(buffer)) != -1) {
      outputStream.write(buffer, 0, bytesRead);
    }
    inputStream.close();
    outputStream.flush();
    writer.append(LINE_FEED);
    writer.flush();
  }

  public static String finish(PrintWriter writer, HttpURLConnection httpConn, OutputStream stream) throws IOException {
    String line = null;
    writer.append(LINE_FEED).flush();
    writer.append("----" + boundary + "--").append(LINE_FEED);
    writer.close();
    stream.close();

    // checks server's status code first
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpConn.getInputStream()));
        while ((line += reader.readLine()) != null) {
        }
        reader.close();
        httpConn.disconnect();
    } else {
        throw new IOException("PRINTING " + httpConn.getResponseMessage() + " " + httpConn.getResponseCode() + " "); //prints 500 internal server error
    }

    return line;
  }
}

quando provo a caricare un’immagine usando Node.js funziona perfettamente. E ho anche testato usando Postman e funziona perfettamente. Ma per qualche motivo c’è qualcosa che mi sono perso in Java.
Ecco il log del server

Started POST "/uploads.json" for 127.0.0.1 at 2022-06-17 18:23:43 +0530
Processing by UploadsController#create as JSON
Completed 500 Internal Server Error in 0ms (ActiveRecord: 0.0ms | Allocations: 157)


EOFError (EOFError)
lib/auth/default_current_user_provider.rb:127:in `current_user'
lib/current_user.rb:36:in `current_user'
app/controllers/application_controller.rb:976:in `rate_limit_crawlers'
lib/middleware/omniauth_bypass_middleware.rb:71:in `call'
lib/content_security_policy/middleware.rb:12:in `call'
config/initializers/100-quiet_logger.rb:23:in `call'
config/initializers/100-silence_logger.rb:31:in `call'
lib/middleware/missing_avatars.rb:23:in `call'
lib/middleware/turbo_dev.rb:34:in `call'
  Rendering layout /home/devarsh/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/actionpack-7.0.3/lib/action_dispatch/middleware/templates/rescues/layout.erb
  Rendering /home/devarsh/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/actionpack-7.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
  Rendered /home/devarsh/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/actionpack-7.0.3/lib/action_dispatch/middleware/templates/rescues/_message_and_suggestions.html.erb (Duration: 0.8ms | Allocations: 382)
  Rendered /home/devarsh/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/actionpack-7.0.3/lib/action_dispatch/middleware/templates/rescues/_actions.html.erb (Duration: 0.4ms | Allocations: 186)
  Rendered /home/devarsh/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/actionpack-7.0.3/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (Duration: 3.3ms | Allocations: 3201)
  Rendered /home/devarsh/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/actionpack-7.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (Duration: 2.1ms | Allocations: 2119)
  Rendering /home/devarsh/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/actionpack-7.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
  Rendered /home/devarsh/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/actionpack-7.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (Duration: 1.0ms | Allocations: 459)
  Rendered /home/devarsh/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/actionpack-7.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (Duration: 18.1ms | Allocations: 9875)
  Rendered layout /home/devarsh/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/actionpack-7.0.3/lib/action_dispatch/middleware/templates/rescues/layout.erb (Duration: 20.4ms | Allocations: 10943)

Per favore, guidami su come posso farlo funzionare usando il pacchetto java.net

Qualsiasi aiuto sarà apprezzato

Modifica: Sto anche allegando il codice Node.js che ha funzionato

var fs = require("fs");
var request = require("request");

fs.readFile("/home/devarsh/Desktop/small2.jpeg", function(e, data) {
    console.log(data, e)
    var options = { method: 'POST',
      url: 'http://localhost:4200/uploads.json',
      headers:
       {
         'api-username': 'tester',
         'api-key': '3772adba123b1db43f4d3644382b97a5ba9b6cdfdb796e25341dc796c402638e',
         'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',
        },
      formData:
       { type: 'image',
         synchronous: 'true',
         file:
          { value: data,
            options: { filename: 'small2.jpeg', contentType: "image/png", } } } };

    request(options, function (error, response, body) {
      if (error) throw new Error(error);

      console.log(body, response.body, error);
    });

})