jenkins 版本 1.6.10
不多说,如果你还没搞定这个接口,请运行下面的代码,帮你创建一个 jenkins 任务
@Test
public void post_xml() throws IOException {
String server = "127.0.0.1:8080" ;
String jenkinsHost = "http://"+server+"/" ;
String projectName = "TEST44" ;
String configurationFile = "D:\\workspace\\Qone\\target\\classes\\jobTemplate\\demo.xml";
String username = "xxxxxxxx";
String apiToken = "xxxxxxxxxxxxxxxxxxxxxxxx" ;
HttpClient client = new HttpClient();
client.getState().setCredentials(
new AuthScope(server,443,"realm"),
new UsernamePasswordCredentials(username,apiToken)
);
client.getParams().setAuthenticationPreemptive(true);
PostMethod post = new PostMethod(jenkinsHost+"/createItem?name="+projectName);
post.setDoAuthentication(true);
File fileInput = new File(configurationFile);
RequestEntity requestEntity = new FileRequestEntity(fileInput,"text/xml; charset=UTF-8");
post.setRequestEntity(requestEntity);
int code = client.executeMethod(post);
System.out.print(post.getResponseBodyAsString());
}
https://github.com/RisingOak/jenkins-client 有人已经在此处封装了jenkins 的操作API ,可以下载直接使用,但其创建任务的方法我没有走通,我这边问题出在 crumb 的获取,此地址在我的 jenkins 服务上访问不了 ,于是另寻出路
if (crumbFlag == true) {
Crumb crumb = get("/crumbIssuer", Crumb.class);
if (crumb != null) {
request.addHeader(new BasicHeader(crumb.getCrumbRequestField(), crumb.getCrumb()));
}
}
查看jenkins 用户信息,点击设置,看到 API TOKEN 一项信息
于是找到这篇文章 https://wiki.jenkins-ci.org/display/JENKINS/Authenticating+scripted+clients
文章中给出了 groovy script 生成任务的方法,于是根据 个人groovy 的逻辑写出上述 JAVA 实现 。
运行结果