java调用jenkins的job
时间: 2025-04-03 08:07:16 浏览: 36
### 如何通过 Java 代码触发 Jenkins Job
为了实现通过 Java 调用 Jenkins API 来触发远程构建的任务,可以利用 `Jenkins Java 客户端 API` 或者基于 RESTful 接口的方式。以下是具体的解决方案:
#### 方法一:使用 Jenkins Java 客户端 API
Jenkins Java 客户端 API 提供了一个简单的方式来管理和控制 Jenkins 实例中的各种资源[^1]。
```java
import hudson.model.*;
import jenkins.model.Jenkins;
import java.util.Collections;
public class JenkinsClientExample {
public static void main(String[] args) throws Exception {
// 连接到 Jenkins 实例
String serverUrl = "http://your-jenkins-server";
String username = "your-username";
String passwordOrToken = "your-password-or-api-token";
JenkinsServer jenkins = new JenkinsServer(new URI(serverUrl), username, passwordOrToken);
try {
// 获取指定的 Job
Job job = jenkins.getJob("job-name");
// 构建 Job (无参数)
QueueReference queueItem = job.build();
System.out.println("Build queued with ID: " + queueItem.getId());
// 如果需要等待构建完成并获取结果
Build build = queueItem.waitForStart();
if (build != null) {
Result result = build.getResult();
System.out.println("Build completed with result: " + result.toString());
}
} finally {
jenkins.close();
}
}
}
```
上述代码展示了如何连接到 Jenkins 并触发一个名为 `"job-name"` 的任务。需要注意的是,在实际应用中可能还需要处理异常以及设置代理等额外配置。
#### 方法二:使用 Rest API 和 HttpClient
如果不想依赖于第三方库,则可以直接调用 Jenkins 的 REST API。下面是一个简单的例子展示如何发送 HTTP 请求来触发改方法下的构建过程[^2]。
```java
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.util.EntityUtils;
public class JenkinsRestApiExample {
public static void main(String[] args) throws Exception{
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials("admin", "password"));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build();
try {
HttpPost post = new HttpPost("http://localhost:8080/job/example/build");
HttpResponse response = httpclient.execute(post);
EntityUtils.consume(response.getEntity());
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Status Code:" + statusCode);
}finally{
httpclient.close();
}
}
}
```
这段程序片段说明了怎样借助 Apache HttpClient 类库向目标 URL 发起 POST 请求从而启动特定名称为 example 的工程构建动作。
注意事项:
- 需要确保 Jenkins 已经启用了相应的权限以便外部系统能够成功发起请求。
- 对于有 CSRF防护机制开启的情况,记得加入 crumb 数据作为头部信息的一部分[^3]。
---
阅读全文
相关推荐


















