Add Attachment to Jira via REST API

こ雲淡風輕ζ 提交于 2019-12-18 04:24:08

问题


I'm trying to post an attachment o JIRA using the latest REST API. Here's my code:

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;
}

However, i get the following response:

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

An Issue with key TEST-2 does exist in the my local JIRA instance and I can add the attachment "by hand" in the Jira app itself. I know that i must add a header of type "X-Atlassian-Token:nocheck" to prevent XSRF, but, by the output, I must be doing something wrong.. What confuses me even further is that a 404 is thrown after the XSRF check failed.

I've scavenged google for answers with no success Can anyone hazard a guess to what I'm doing wrong?


回答1:


I've managed to resolve the issue by using the apache http client For whom may have the same issue, here's the code:

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;

}



回答2:


@Nuno Neto, I'm surprised your method is working, as it's missing some key elements in the FileBody. Possible update to the Confluence API? Most importantly the file comment, and the encoding. As it were, your example will throw a 500, but for new people coming to this via Google the code below will in fact work.

The major difference here would be:

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

I also have added a small bit of logic for empty file comments.

/**************************************************************************************************
 /**
 * 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;
    }
};


来源:https://stackoverflow.com/questions/18631361/add-attachment-to-jira-via-rest-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!