在asanaapi上使用java的httppost多部分/表单数据上传文件

vfh0ocws  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(343)

关闭。这个问题需要更加突出重点。它目前不接受答案。
**想改进这个问题吗?**通过编辑这篇文章更新这个问题,使它只关注一个问题。

5年前关门了。
改进这个问题
如何使用纯java.net将文件附加到使用asanaapi的任务?
具体来说,如何向asanaapi发出格式良好的httppost多部分/表单数据编码请求,以便成功地将文件附加到任务?

6mw9ycah

6mw9ycah1#

asana api期望通过http post请求将附件上载到任务,该请求包含一个多部分/表单数据编码文件:
https://asana.com/developers/api-reference/attachments#upload
正如本回答中关于换行符上的http规范所解释的,请确保您使用的是 \r\n 换行符,因为java将转换最多 println() 与平台相关的方法 line.separator 而且asana服务器可能不能容忍格式不正确的换行。
格式良好的多部分/表单数据post请求如下所示:

Authorization: Basic <BASE64_ENCODED_AUTH>
Content-Type: multipart/form-data; boundary=14d07d7cbcf
User-Agent: Java/1.7.0_76
Host: localhost:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
Content-Length: 141

--14d07d7cbcf
Content-Disposition: form-data; name="file"; filename="example.txt"
Content-Type: text/plain

A file

--14d07d7cbcf--

这是一个java实现,它纯粹使用java.net类为asana attachments api手动构造一个格式良好的多部分/表单数据编码post请求:

import org.apache.commons.codec.binary.Base64;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class AttachFileToTask {
    // Use HTTP compliant line feeds in the request.
    // Note that Java println() methods may use platform dependent line feeds.
    private static String LINE_FEED = "\r\n";

    public static void main(String[] args) throws Exception {
        // Task attachments endpoint
        String url = "https://app.asana.com/api/1.0/tasks/<TASK_ID>/attachments";
        File theFile = new File("/path/to/file.txt");

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();

        // Set basic auth header
        String apiKey = "<API_KEY>" + ":";
        String basicAuth = "Basic " + new String(new Base64().encode(apiKey.getBytes()));
        connection.setRequestProperty("Authorization", basicAuth);

        // Indicate a POST request
        connection.setDoOutput(true);

        // A unique boundary to use for the multipart/form-data
        String boundary = Long.toHexString(System.currentTimeMillis());

        // Construct the body of the request
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        PrintWriter writer = null;
        try {
            writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));

            String fileName = theFile.getName();
            writer.append("--" + boundary).append(LINE_FEED);
            writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"").append(LINE_FEED);
            writer.append("Content-Type: text/plain").append(LINE_FEED);
            writer.append(LINE_FEED);

            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(new FileInputStream(theFile), "UTF-8"));
                for (String line; (line = reader.readLine()) != null; ) {
                    writer.append(line).append(LINE_FEED);
                }
            } finally {
                if (reader != null) try {
                    reader.close();
                } catch (IOException logOrIgnore) {
                }
            }

            writer.append(LINE_FEED);
            writer.append("--" + boundary + "--").append(LINE_FEED);
            writer.append(LINE_FEED);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            System.out.append("Exception writing file" + e);
        } finally {
            if (writer != null) writer.close();
        }

        System.out.println(connection.getResponseCode()); // Should be 200
        System.out.println(connection.getResponseMessage());
    }
}

请注意,不鼓励在个人使用或开发实用程序脚本之外使用api密钥进行基本身份验证。为多个用户部署生产应用程序时,请使用asana connect(oauth 2.0)

相关问题