gpt4 book ai didi

java - 使用 JAVA 将图像上传到 ActiveCollab API 时出现问题

转载 作者:行者123 更新时间:2023-12-02 05:52:30 24 4
gpt4 key购买 nike

我正在尝试使用 JAVA 将图像上传到自托管的 ActiveCollab。

我已经做了一些测试,对我来说,这个测试是迄今为止最可靠的。不管怎样,当我尝试运行它时,我得到代码 200-OK 和一个空数组作为响应。 。

public static void main(String args[]) throws IOException  {



URL url = new URL("<SITE>/api/v1/upload-files");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setDoOutput(true);
c.setRequestProperty("Content-Type", "multipart/form-data");
c.setRequestProperty("X-Angie-AuthApiToken", "<TOKEN>");

JSONArray array = new JSONArray();
array.put("/test.png");
array.put("image/png");

OutputStream out = c.getOutputStream();
out.write(array.toString().getBytes());
out.flush();
out.close();

BufferedReader buf = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuffer response = new StringBuffer();
String line;
while (null != (line = buf.readLine())) {
response.append(line);
}

JSONArray message = new JSONArray(response.toString());
System.out.println(message);

}

在 API 文档中,我应该得到一个填充的 json 数组作为响应。事实上我不知道我错过了什么。

最佳答案

终于解决了!正如 @StephanHogenboom 所说,问题出在 multipart/form-data 中,参数必须在那里引入,而不是通过 JSONArray 引入。我没有找到太多关于如何在 java.net 中使用 multipart 的信息,但至少我找到了一种已弃用但实用的工作方式。

public static void main(String args[]) throws IOException  {



URL url = new URL("<SITE>/api/v1/upload-files");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setDoOutput(true);
c.setRequestMethod("POST");
c.setRequestProperty("X-Angie-AuthApiToken", "<TOKEN>");

File file = new File("/1.png");
FileBody fileBody = new FileBody(file, "image/png");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
multipartEntity.addPart("file", fileBody);

c.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());

OutputStream out = c.getOutputStream();
multipartEntity.writeTo(out);
out.close();

BufferedReader buf = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuffer response = new StringBuffer();
String line;
while (null != (line = buf.readLine())) {
response.append(line);
}

JSONArray message = new JSONArray(response.toString());
System.out.println(message);

}

实际上它对我有用,但如果有人能给我关于如何改进的想法那就太好了!

关于java - 使用 JAVA 将图像上传到 ActiveCollab API 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56038065/

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