java - 使用 JAVA 将图像上传到 ActiveCollab API 时出现问题
问题描述
我正在尝试将带有 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 所说,问题出在多部分/表单数据中,必须在那里引入参数,而不是通过 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);
}
实际上它对我有用,但如果有人能给我关于如何改进的想法,那就太好了!
推荐阅读
- django - Django 不明白我在数据库中的字段是否为空
- shell - 如何从 unix 中的 json 文件中提取值?
- excel - Excel - 根据设定条件突出显示行
- python - Python UiPath - 如何在 UiPath.Python.Activities 中使用类
- node.js - Raspberry Pi 断电时更改文本文件
- emscripten - Emscripten 传递 stl c++ map 参数
- javascript - 滑块图像已满时如何制作?反应式
- python - 关于导入 Python 的错误
- react-native - 如何在激活其他组件中的道具后重新渲染已经渲染的组件
- apache-spark - 火花工作卡住的原因可能是什么