【问题标题】:Asana API - Adding an attachment to a task through JavaAsana API - 通过 Java 向任务添加附件
【发布时间】:2015-03-09 23:38:07
【问题描述】:

我一直在尝试通过 Asana API 将附件上传到任务中,但到目前为止没有成功。使用 curl 我可以正常工作:

curl -u <api_key>: --form "file=@<path_to_file>" https://app.asana.com/api/1.0/tasks/<task_id>/attachments

但我无法通过 Java 执行它。我发现的几篇关于它的帖子提到它应该是多部分/表单数据,所以我一直在尝试我在其他地方使用过的不同版本的工作多部分/表单数据上传代码。我不断收到回复:

file: Missing input

基本上,代码如下所示:

Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "multipart/form-data");
headers.put("Authorization", "Basic " + encodedCreds);
Path p = Paths.get(filePath);
String fileName = p.getFileName().toString();
headers.put("Content-Disposition", "form-data; name=\"" + "file" + "\"; filename=\"" + fileName + "\"");

url = new URL(urlStr);
conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod(method);

if(headers != null) {
    for(Map.Entry<String, String> headerEntry : headers.entrySet()){
        conn.setRequestProperty(headerEntry.getKey(), headerEntry.getValue());
    }
}

conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
FileInputStream inputStream = new FileInputStream(filePath);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
    wr.write(buffer, 0, bytesRead);
}
inputStream.close();
wr.flush();
wr.close();

我尝试更改 filePath 以包含预期参数的 JSON(来自我读过的其他帖子),例如:

{"data" : { "id": <taskId> , "file" : @<filePath> } }

{"files" : { "file" : @<filePath> } }

以及它的其他变体。似乎没有任何效果,我不确定接下来要尝试什么。

【问题讨论】:

    标签: java attachment asana


    【解决方案1】:

    这看起来类似于之前关于 SO 的问题:Asana Api Rails Attachment

    请注意,文件上传中的文件需要作为表单编码的 POST 正文发送,而不是作为 JSON 正文中的字符串发送。它模拟普通的基于表单的文件上传,就像浏览器发送它一样。您的 Java 库可能有能力做这样的事情。 curl 中的 @ 符号实际上并不是上传的一部分 - 它只是告诉 curl “在此处包含一个文件”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多