通过REST API向Jira添加附件

时间:2013-09-05 08:27:51

标签: java rest jira attachment

我正在尝试使用最新的REST API发布JIRA附件。 这是我的代码:

public boolean addAttachmentToIssue(String issueKey, String path){

        String auth = new 

String(org.apache.commons.codec.binary.Base64.encodeBase64((user+":"+pass).getBytes()));


    Client client = Client.create();
    WebResource webResource = client.resource(baseURL+"issue/"+issueKey+"/attachments");


    FormDataMultiPart formDataMultiPart = new FormDataMultiPart();

        File f = new File(path);
        if(f.exists() && f.isFile()){
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(f);
            } catch (FileNotFoundException e) {
                return false;
            }

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            try {
                for (int readNum; (readNum = fis.read(buf)) != -1;) {
                    bos.write(buf, 0, readNum); //no doubt here is 0
                }
                fis.close();
                bos.close();
            } catch (IOException ex) {
                try {
                    fis.close();
                    bos.close();
                } catch (IOException e) {
                    return false;
                }
                return false;
            }
            byte[] bytes = bos.toByteArray();

            FormDataBodyPart bodyPart = new FormDataBodyPart("file", new ByteArrayInputStream(bytes), MediaType.APPLICATION_OCTET_STREAM_TYPE);
             formDataMultiPart.bodyPart(bodyPart);
    }else{
        return false;
    }

    ClientResponse response = null;

    response = webResource.header("Authorization", "Basic " + auth).header("X-Atlassian-Token", "nocheck").type(MediaType.MULTIPART_FORM_DATA).accept("application/json").post(ClientResponse.class, formDataMultiPart);
    System.out.println(response);

    int statusCode = response.getStatus();
    System.out.println(statusCode);
    String resp = response.getEntity(String.class);
    System.out.println(resp);

    return true;
}

但是,我收到以下回复:

POST http://localhost:8082/rest/api/2/issue/TEST-2/attachments returned a response status of 404 Not Found
404
XSRF check failed

我的本​​地JIRA实例中存在密钥TEST-2的问题,我可以在Jira应用程序本身中“手动”添加附件。 我知道我必须添加一个类型为“X-Atlassian-Token:nocheck”的标题以防止XSRF,但是,通过输出,我一定是做错了什么.. 令我更加困惑的是,在XSRF检查失败后抛出404。

我已经清除谷歌的答案但没有成功 谁能冒险猜测我做错了什么?

2 个答案:

答案 0 :(得分:3)

我已设法通过使用apache http客户端来解决此问题 对于谁可能有同样的问题,这是代码:

public boolean addAttachmentToIssue(String issueKey, String path){


        String auth = new String(org.apache.commons.codec.binary.Base64.encodeBase64((user+":"+pass).getBytes()));


    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(baseURL+"issue/"+issueKey+"/attachments");
    httppost.setHeader("X-Atlassian-Token", "nocheck");
    httppost.setHeader("Authorization", "Basic "+auth);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    File fileToUpload = new File(path);
    FileBody fileBody = new FileBody(fileToUpload, "application/octet-stream");
    entity.addPart("file", fileBody);

    httppost.setEntity(entity);
    HttpResponse response = null;
    try {
        response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
    HttpEntity result = response.getEntity();

    if(response.getStatusLine().getStatusCode() == 200)
        return true;
    else
        return false;

}

答案 1 :(得分:1)

<@> @Nuno Neto,我很惊讶你的方法正在运行,因为它缺少FileBody中的一些关键元素。可能更新Confluence API?最重要的是文件注释和编码。事实上,你的例子会抛出一个500,但对于通过谷歌来到这里的新人来说,下面的代码实际上是可行的。

这里的主要区别是:

FileBody fileBody = new FileBody(fileToUpload, fileComment, "application/octet-stream", "UTF-8");

我还为空文件注释添加了一些逻辑。

/**************************************************************************************************
 /**
 * Confluence integration. This allows the user to attach captured images to confluence pages.
 *
/**************************************************************************************************/
/**
 *
 * @param pageID {int} Page ID of the Confluence page to add to. Navigate to Confluence page, hit 'e', copy the ID from the URI.
 * @param {String} path 
 * @param {String} user Your Confluence username.
 * @param {String} pass Your Confluence password.
 * @param {String} baseURL Your Confluence url.
 * @return {boolean}
 */

public boolean addAttachmentToPage(int pageID, String path, String user, String pass, String baseURL, String fileComment){
    String auth = new String(org.apache.commons.codec.binary.Base64.encodeBase64((user+":"+pass).getBytes()));

    if ( fileComment.equals("") | fileComment.equals(" ") | fileComment.equals(null)){
        fileComment = user + "-" + path;
    };

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost( baseURL + "/rest/api/content/" + pageID + "/child/attachment" );
    httppost.setHeader("X-Atlassian-Token", "nocheck");
    httppost.setHeader("Authorization", "Basic "+auth);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    File fileToUpload = new File(path);
    FileBody fileBody = new FileBody(fileToUpload, fileComment, "application/octet-stream", "UTF-8");
    entity.addPart("file", fileBody);

    httppost.setEntity(entity);
    HttpResponse response = null;
    try {
        response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
    HttpEntity result = response.getEntity();

    // Success!
    if(response.getStatusLine().getStatusCode() == 200) {
        System.out.println("Confluence -> Exported to the page with ID: " + confPageID);
        return true;
    }
    else {
        System.out.println("Confluence -> Error : " + response.getStatusLine().getStatusCode());
        System.out.println(response + "\n" + "\n" + response.getAllHeaders() + "\n" + result + "\n" + path + "\n" + "Attempted against: " + baseURL + "/rest/api/content/" + pageID + "/child/attachment" + "\n");
        return false;
    }
};