3

最新の 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

キー TEST-2 の課題がローカル JIRA インスタンスに存在し、Jira アプリ自体に「手動で」添付ファイルを追加できます。XSRF を防ぐために「X-Atlassian-Token:nocheck」タイプのヘッダーを追加する必要があることはわかっていますが、出力を見ると、何か間違ったことをしているに違いありません。 XSRF チェックに失敗しました。

私はグーグルで答えを探しましたが、成功しませんでした。誰かが私が間違っていることを推測する危険を冒すことはできますか?

4

2 に答える 2

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;

}
于 2013-09-06T11:27:22.257 に答える
1

@Nuno Neto、FileBodyにいくつかの重要な要素が欠けているため、あなたのメソッドが機能していることに驚いています。Confluence API の更新の可能性はありますか? 最も重要なのは、ファイルのコメントとエンコーディングです。いわば、あなたの例は 500 をスローしますが、Google 経由でこれに来る新しい人にとっては、実際には以下のコードが機能します。

ここでの主な違いは次のとおりです。

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;
    }
};
于 2015-05-28T18:34:46.123 に答える