java - 使用Java以表单数据上传文件

标签 java apache http

我正在尝试使用 Apache API 在 Java 中执行 HTTP Post 请求。

使用curl,请求看起来像这样

curl https://host/upload
-X POST
-H "Authorization: Bearer xxx"
-H "Content-Type: multipart/form-data"
-H "Accept: application/json"
-F "file=@{PathToImage}" -F "type=file" 

虽然在使用 CURL 运行时工作正常,但在使用以下 Java 代码运行时服务器返回 500er 结果

    final HttpPost httppost = new HttpPost("https://host/upload");
    httppost.addHeader("Authorization", "Bearer xxx");
    httppost.addHeader("Accept", "application/json");
    httppost.addHeader("Content-Type", "multipart/form-data");

    final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    final File file = new File("c:\\tmp\\myfile.pdf");
    builder.addBinaryBody("file", file);
    builder.addTextBody("type", "file");
    final HttpEntity entity = builder.build();
    httppost.setEntity(entity);
    final HttpResponse response = httpclient.execute(httppost);
    httpclient.close();

知道我在这里缺少什么吗?

最佳答案

This问题是类似的。但我相信答案是将您的 addBinary 更改为 addPart。

final HttpPost httppost = new HttpPost("https://host/upload");
httppost.addHeader("Authorization", "Bearer xxx");
httppost.addHeader("Accept", "application/json");
httppost.addHeader("Content-Type", "multipart/form-data");

final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
final File file = new File("c:\\tmp\\myfile.pdf");
builder.addPart("file", new FileBody(file));
builder.addTextBody("type", "file");
final HttpEntity entity = builder.build();
httppost.setEntity(entity);
final HttpResponse response = httpclient.execute(httppost);
httpclient.close();

关于java - 使用Java以表单数据上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58780432/

相关文章:

java - 这是什么设计模式——适配器、提供者、委托(delegate)、模板方法,还是……?

java - Apache POI : Retrieve page number from XWPFParagraph instance?

spring-boot - Apache Camel 处理 http 请求时出现异常

Java:如何处理/解析传入的 HTTP 请求?

java - 如何创建一个位于 android 项目之外的 java 包

java - 你有 Hibernate 实体的通用基类吗?

apache - SSL 应用于太多域

c# - 如何在返回前等待回调

java - Android ImageView - 填充宽度和调整大小以保持纵横比

python - 使用 apache 和 mod_wsgi 的 Flask hello world 仅在 webroot 中显示文件