Raji
Raji

Reputation: 887

How to use REST API to POST using Java for Jenkins

I am a new learner in java space. I need to create jenkins job using REST API. I am able to connect to Jenkins and list all jobs in it(GET method). I want to know how do I post to it.

My plan is to create a json file with input data to create job and java program will read it(json file) and post it to Jenkins and create job. I searched little bit about post. I could get few examples where some String data is posted. How do I post json file data to Jenkins and also it creates a job in Jenkins?

Can I get a small code snippet so that I can refer it or a sample Java program?

Thank you

Upvotes: 1

Views: 5583

Answers (1)

João Marcos
João Marcos

Reputation: 3972

You can see the Jenkins API page. You can fill in the gaps using the documentation provided by Jenkins itself; for example, http://JENKINS_HOST/api will give you the URL for creating a job and http://JENKINS_HOST/job/JOBNAME/api will give you the URL to trigger a build.

After this you can use Java and Jersey to create a rest client.

Declares jersey-client in your maven pom

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.8</version>
</dependency>

And then create client with the code above example:

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

public static void main(String[] args) {

  try {

    Client client = Client.create();

    WebResource webResource = client
       .resource("http://JENKINS_HOST/job/JOBNAME/api");

    String input = "{\"key1\":\"value1\",\"key2\":\"value2\"}";

    ClientResponse response = webResource.type("application/json")
       .post(ClientResponse.class, input);

    if (response.getStatus() != 201) {
        throw new RuntimeException("Failed : HTTP error code : "
             + response.getStatus());
    }

    System.out.println("Output from Server .... \n");
    String output = response.getEntity(String.class);
    System.out.println(output);

  } catch (Exception e) {

    e.printStackTrace();

  }

 }
}

Upvotes: 2

Related Questions