我正在尝试使用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数组作为响应。其实我不知道我缺少什么。
答案 0 :(得分:0)
最后我解决了!正如@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);
}
实际上它对我有用,但是如果有人可以给我有关如何改进的想法,那将是很棒的!