public static void main(String[] args){
Map attachments = new HashMap();
try {
//fileName是附件名称,filePath 是文件路径
attachments.put("fileName", new FileInputStream(new File("filePath")));
issueUploadAttachment(issueKey,attachments);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}/**
* issue上传附件
*
* @param issueKey---创建缺陷成功后返回的key.
* @param attachments
* @throws Exception
*/
public static void issueUploadAttachment(String issueKey, Map attachments) throws Exception {
Map headers = new HashMap<>();
//添加鉴权
headers.put("Authorization", "Basic xxxx");
for (String key : attachments.keySet()) {
//上传附件
uploadAttachment("http://you jira address:port/rest/api/2/issue/" + issueKey + "/attachments", headers, attachments.get(key), key);
}
}
/**
* 上传附件,附件需要特殊处理下,重写http请求方法
*
* @param url
* @param headers
* @param inputStream
* @param fileName
* @throws Exception
*/
public static void uploadAttachment(String url, Map headers,
InputStream inputStream, String fileName) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
HttpPost httppost = new HttpPost(url);
for (String key : headers.keySet()) {
httppost.setHeader(key, headers.get(key));
}
httppost.setHeader("X-Atlassian-Token", "no-check");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", inputStream, ContentType.create("multipart/form-data", Consts.UTF_8),
fileName);
HttpEntity reqEntity = builder.build();
httppost.setEntity(reqEntity);
response = httpclient.execute(httppost);
if (response != null && response.getStatusLine() != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseEntityStr = EntityUtils.toString(response.getEntity());
JSONArray jsonArray = JSONArray.fromObject(responseEntityStr);
if (jsonArray != null && jsonArray.size() > 0) {
EntityUtils.consume(resEntity);
return;
}
}
}
logger.error("issue uploadAttachments fail");
} catch (Exception e) {
e.printStackTrace();
} finally {
response.close();
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 移动issues到sprint
*
* @param jiraSprintId sprintId
* @param issueKey 创建缺陷返回的key
*/
public static void moveIssuesToSprint(String jiraSprintId, String issueKey) {
JSONArray jsonArray = new JSONArray();
jsonArray.add(issueKey);
JSONObject jsonObject = new JSONObject();
jsonObject.put("issues", jsonArray);
//jsonObject 作为body请求
httpClient("post", "http://you jira address:port/rest/agile/1.0/sprint/" + jiraSprintId + "/issue", jsonObject.toString());
}