Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at

Wednesday, January 3, 2018

Jenkins Restful API with Java : Create, abort, build new jobs using API

Jenkins RestFul APIs for Abort, Creating and Building a Job.

How to abort a Jenkins Job using REST API in java.

Below is the Java method to abort a jenkins Job using REST API.

Please note you can use your own api client to post this request.

Please change the IP and PORT according to your Jenkins IP and PORT.

public  String abortJob(String jobName, String buildNumber) {
  String abortURL = "" + jobName + "/"+buildNumber+"/stop";
  Client client = Client.create();

  client.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter("taas", "taas"));
  WebResource webResource = client.resource(abortURL);
  ClientResponse response = webResource.type("application/xml").post(ClientResponse.class, null);
  String jsonResponse = response.getEntity(String.class);
  return jsonResponse;


How to get the list of all idle nodes from Jenkins using REST API in java.

Please change ip address with your jenkins IP and port


public ArrayList<String> getIdleVmsList() {

  String response = callAPI("");
  return parseResponse(response);


 public ArrayList<String> parseResponse(String response) {

  ArrayList<String> idleVm = new ArrayList<String>();

  JSONObject stat = new JSONObject(response);
  JSONArray computer = stat.getJSONArray("computer");

  for (int i = 0; i < computer.length(); i++) {
   JSONObject info = (JSONObject) computer.get(i);
   String master = (String) info.get("displayName");
   Boolean vmOfflineStatus = (Boolean) info.get("offline");
   Boolean vmIdleStatus = (Boolean) info.get("idle");
   if (!vmOfflineStatus && vmIdleStatus && !master.equalsIgnoreCase("master")) {
    idleVm.add((String) info.get("displayName"));



  return idleVm;


 public static String callAPI(String Url) {
  Client client = Client.create();
  try {
   client.addFilter(new HTTPBasicAuthFilter("username", "pwd"));
   WebResource webResource = client.resource(Url);
   ClientResponse response = webResource.get(ClientResponse.class);
   String jsonResponse = response.getEntity(String.class);

   return jsonResponse;
  } catch (Exception e) {
   return "couldnot call jenkins get API";


How to build a job using REST API. 



where JobName is the name of your jenkins job.

Please contact us for more Restful web services of Jenkins. 

No comments: