Как я могу выполнить multipart/form-data запрос POST с помощью Java?

Вы не можете читать и писать из / в один и тот же файл одновременно. Не с StreamReader и StreamWriter, ни с любым другим обычным методом. Если вам необходимо изменить существующий файл и не можете (или не хотите) читать весь его контент в памяти, вы должны записать измененный контент во временный файл, а затем заменить оригинал на временный файл после закрытия обоих файлов.

Пример:

$filename = (Get-Item $file).Name

$streamReader = New-Object IO.StreamReader -Arg $file
$streamWriter = [System.IO.StreamWriter] "$file.tmp"

...

$streamReader.Close(); $streamReader.Dispose()
$streamWriter.Close(); $streamWriter.Dispose()

Remove-Item $file -Force
Rename-Item "$file.tmp" -NewName $filename
87
задан 4 September 2009 в 12:27
поделиться

4 ответа

Мы используем HttpClient 4.x для публикации составных файлов.

ОБНОВЛЕНИЕ : Начиная с HttpClient 4.3 , некоторые классы устарели. Вот код с новым API:

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("...");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN);

// This attaches the file to the POST:
File f = new File("[/path/to/upload]");
builder.addBinaryBody(
    "file",
    new FileInputStream(f),
    ContentType.APPLICATION_OCTET_STREAM,
    f.getName()
);

HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();

Ниже приведен исходный фрагмент кода с устаревшим API HttpClient 4.0 :

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);

FileBody bin = new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);

HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
144
ответ дан 24 November 2019 в 07:44
поделиться

Мое сообщение кода multipartFile к серверу.

  public static HttpResponse doPost(
    String host,
    String path,
    String method,
    MultipartFile multipartFile
  ) throws IOException
  {

    HttpClient httpClient = wrapClient(host);
    HttpPost httpPost = new HttpPost(buildUrl(host, path));

    if (multipartFile != null) {

      HttpEntity httpEntity;

      ContentBody contentBody;
      contentBody = new ByteArrayBody(multipartFile.getBytes(), multipartFile.getOriginalFilename());
      httpEntity = MultipartEntityBuilder.create()
                                         .addPart("nameOfMultipartFile", contentBody)
                                         .build();

      httpPost.setEntity(httpEntity);

    }
    return httpClient.execute(httpPost);
  }
0
ответ дан 24 November 2019 в 07:44
поделиться

http-компоненты-клиент-4.0.1 работали на меня. Однако, мне пришлось добавить внешнюю банку apache-mime4j-0.6.jar (org.apache.james.mime4j) иначе. reqEntity.addPart("bin", bin); не будет компилироваться. Теперь он работает как шарм.

2
ответ дан 24 November 2019 в 07:44
поделиться

Это зависимости Maven, которые у меня есть.

Код Java:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

FileBody uploadFilePart = new FileBody(uploadFile);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("upload-file", uploadFilePart);
httpPost.setEntity(reqEntity);

HttpResponse response = httpclient.execute(httpPost);

Зависимости Maven в pom.xml:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.0.1</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpmime</artifactId>
  <version>4.0.1</version>
  <scope>compile</scope>
</dependency>
39
ответ дан 24 November 2019 в 07:44
поделиться
Другие вопросы по тегам:

Похожие вопросы: