首页 > 解决方案 > 使用 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 数组作为响应。其实我不知道我错过了什么。

标签: javajsonhttpurlconnectionactivecollab

解决方案


最后我解决了!正如@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);

    }

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


推荐阅读