gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:53:17 26 4
gpt4 key购买 nike

我正在尝试使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com