Запрос на java тип multipart/form-data через StringBuilder

Необходимо написать запрос к методу API (chunked-file/send) для выкладывания архива на ресурс по примеру:

Запрос

--92b6ce48-f570-4fd9-959b-639e9eee1929
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=chunkNumber

1
--92b6ce48-f570-4fd9-959b-639e9eee1929
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=totalChunks

10
--92b6ce48-f570-4fd9-959b-639e9eee1929
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=fileSize

9731899
--92b6ce48-f570-4fd9-959b-639e9eee1929
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=id


--92b6ce48-f570-4fd9-959b-639e9eee1929
Content-Type: application/octet-steam
Content-Disposition: form-data; filename= ********; name=chunk

{… Binary data file content…}

Реализовал через StringBuilder

Данный запрос возвращает Id для следующего метода text-message/send Вопрос в том, что если не указать кодировку .getBytes("WINDOWS-1251"), то метод text-message/send возвращает ошибку 500. Если оставить так как есть то на русурсе не могут прочитать отправленный файл. Понятно, что что то с кодировкой, но куда копать не понятно.

Код:

File target = new File( ссылка на файл );
gHttps = gHttp + "/chunked-file/send";
try {
    // Путь к файлу, который нужно отправить
    fSzs = (int) target.length();
    Path filePath = Paths.get( target.toString() );
    byte[] fileBytes = Files.readAllBytes(filePath);
    int totalChunks = (int) Math.ceil( fSzs / (double ) 3_000_000); // Максимум 3 МБ на часть
    for (int chunkNumber = 0; chunkNumber < totalChunks; chunkNumber++) {
        int start = chunkNumber * 3_000_000;
        int end = Math.min(start + 3_000_000, fSzs);
        byte[] chunk = new byte[end - start];
                System.arraycopy(fileBytes, start, chunk, 0, end - start);
        sendChunk(target.getName(), chunkNumber + 1, totalChunks, fSzs, chunk);
    }
    gHttps = gHttp + "/text-message/send";
    request = HttpRequest.newBuilder()
        .uri( URI.create(gHttps) )
        .setHeader("Content-Type", "application/json")
        .header( "Authorization", "Bearer " + cJWT )
        .POST( HttpRequest.BodyPublishers.ofString( "{\"idFile\":\"" + cId + " \",}" ) )
        .build();
} catch (IOException | InterruptedException e) {
    e.printStackTrace();
}

private static void sendChunk (String nfls, int chunkNumber, int totalChunks, int fileSize, byte[] chunk) throws IOException, InterruptedException {
    String boundary = BOUNDARY;
    StringBuilder requestBody = new StringBuilder();
    requestBody.append("--").append(boundary).append(LINE_FEED);
    requestBody.append("Content-Type: text/plain; charset=utf-8").append(LINE_FEED);
    requestBody.append("Content-Disposition: form-data; name=chunkNumber").append(LINE_FEED).append(LINE_FEED);
    requestBody.append(chunkNumber).append(LINE_FEED);

        requestBody.append("--").append(boundary).append(LINE_FEED);
        requestBody.append("Content-Type: text/plain; charset=utf-8").append(LINE_FEED);
        requestBody.append("Content-Disposition: form-data; name=totalChunks").append(LINE_FEED).append(LINE_FEED);
        requestBody.append(totalChunks).append(LINE_FEED);
        requestBody.append("--").append(boundary).append(LINE_FEED);
        requestBody.append("Content-Type: text/plain; charset=utf-8").append(LINE_FEED);
        requestBody.append("Content-Disposition: form-data; name=fileSize").append(LINE_FEED).append(LINE_FEED);
        requestBody.append(fileSize).append(LINE_FEED);
        requestBody.append("--").append(boundary).append(LINE_FEED);
        requestBody.append("Content-Type: text/plain; charset=utf-8").append(LINE_FEED);
        requestBody.append("Content-Disposition: form-data; name=Id").append(LINE_FEED).append(LINE_FEED);
        requestBody.append("").append(LINE_FEED); // Идентификатор отсутствует при первом обращении
        requestBody.append("--").append(boundary).append(LINE_FEED);
        requestBody.append("Content-Type: application/octet-stream").append(LINE_FEED);
        requestBody.append("Content-Disposition: form-data; filename=" + nfls + "; name=chunk").append(LINE_FEED).append(LINE_FEED);
    // Добавляем данные чанка
    requestBody.append(new String(chunk)).append(LINE_FEED);
        // Завершаем запрос
        requestBody.append("--").append(boundary).append("--").append(LINE_FEED);
        // Формируем запрос
    HttpRequest request = HttpRequest.newBuilder()
        .uri( URI.create(gHttps) )
        .header("Content-Type", "multipart/form-data; boundary=" + boundary)
        .header( "Authorization", "Bearer " + cJWT )
        .POST(BodyPublishers.ofByteArray( requestBody.toString().getBytes("WINDOWS-1251")) )
        .build();
    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    cId = response.body();
}

Ответы (0 шт):