javajenkinsjenkins-api

Unable to trigger Jenkins build via java


I want to trigger Jenkins to build a job but the below code just retrieves the error 403.

  public static void main(String[] args) {
    try {
        URL url = new URL("http://localhost:8080/job/RPA/build?token=117cdb21bf4c01f8c20ff5cf7e368dba8c"); // Jenkins URL localhost:8080, job named 'test'
        String user = "mahmoud"; // username
        String pass = "zaky"; // password or API token
        String authStr = user + ":" + pass;
        String encoding = Base64.getEncoder().encodeToString(authStr.getBytes("utf-8"));

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Authorization", "Basic " + encoding);
        InputStream content = connection.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
  }

and output is:

java.io.IOException: Server returned HTTP response code: 403 for URL: http://localhost:8080/job/RPA/build?token=117cdb21bf4c01f8c20ff5cf7e368dba8c
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1919)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1515)
    at com.offbytwo.jenkins.model.mainmain.main(mainmain.java:27)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)

I tried searching for this error on internet but I can't find a solution for it, also I want to know how I can know build status via java


Solution

  • i figure out the solution just remove token from URl and added it into password and solved :)