Jenkins Java开发:获取触发构建的用户名
Hey there! To grab the username that started a Jenkins build from that specific page, you’ve got two reliable approaches—let’s break them down:
方法1:使用Jenkins REST API(推荐)
Jenkins provides a built-in REST API that’s way more stable than scraping HTML, since page layouts can change unexpectedly. The build details endpoint returns all the info you need in JSON format.
步骤&代码示例
- 首先,你的Java项目需要依赖JSON解析库,比如Jackson(或者Gson,whichever you prefer)。
- 用Java的HttpClient(Java 11+自带)或者第三方库如OkHttp来发送请求到Jenkins API endpoint:
http://[JENKINS_NAME]/job/[JOB_NAME]/[BUILD_NUMBER]/api/json - 解析返回的JSON,提取
actions.causes.userName字段(这就是启动构建的用户名)。
Here’s a quick code snippet using Java 11 HttpClient and Jackson:
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class JenkinsBuildUserFetcher { public static void main(String[] args) throws Exception { // Replace these placeholders with your actual Jenkins details String jenkinsUrl = "http://[JENKINS_NAME]/job/[JOB_NAME]/[BUILD_NUMBER]/api/json"; String username = "your-jenkins-username"; // If Jenkins requires auth String apiToken = "your-jenkins-api-token"; // Better than using password // Create HTTP client with basic auth if needed HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(jenkinsUrl)) .header("Authorization", "Basic " + java.util.Base64.getEncoder().encodeToString((username + ":" + apiToken).getBytes())) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); // Parse JSON to get the username ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readTree(response.body()); JsonNode causesNode = rootNode.path("actions").get(0).path("causes").get(0); String startedByUser = causesNode.path("userName").asText(); System.out.println("Build started by: " + startedByUser); } }
注意: 如果你的Jenkins实例不需要认证,可以去掉Authorization header那一行。
方法2:HTML页面解析(不推荐,应急用)
If for some reason you can’t use the API, you can scrape the HTML page directly. This is fragile though—if Jenkins updates its UI layout, the code might break.
步骤&代码示例
Use a HTML parsing library like Jsoup to fetch the page and extract the username from the "Started by user [USER_NAME]" text:
import org.jsoup.Jsoup; import org.jsoup.nodes.Document; public class JenkinsHtmlScraper { public static void main(String[] args) throws Exception { String jenkinsBuildUrl = "http://[JENKINS_NAME]/job/[JOB_NAME]/[BUILD_NUMBER]/"; String username = "your-jenkins-username"; String apiToken = "your-jenkins-api-token"; // Fetch the page with auth if needed Document doc = Jsoup.connect(jenkinsBuildUrl) .userAgent("Mozilla/5.0") .auth(username, apiToken) .get(); // Find the element containing the "Started by user" text String startedByText = doc.select("div.build-caption span").first().text(); // Extract the username from the text String userName = startedByText.replace("Started by user ", ""); System.out.println("Build started by: " + userName); } }
提示: You’ll need to add Jsoup dependency to your project (e.g., Maven/Gradle) to use this code.
关键注意事项
- Permissions: Make sure the user account you’re using has permission to view the build details in Jenkins.
- API Tokens: Always use Jenkins API Tokens instead of plain passwords for authentication—you can generate them in your Jenkins user profile.
- Error Handling: The examples above skip error handling for brevity; in production code, add checks for HTTP errors, missing JSON fields, or HTML element changes.
内容的提问来源于stack exchange,提问作者George Cimpoies

