无法通过java代码触发jenkins工作

时间:2018-05-03 11:42:42

标签: java httpurlconnection jenkins-cli

我正试图通过java代码触发jenkins工作。我在线获得了源代码。我无法使其工作。 我不断收到“服务器返回的HTTP错误代码403”

请找到示例代码:

add_filter( 'user_contactmethods', 'extra_contact_info' );

function extra_contact_info( $fields ) {
  $fields['email'] = __( 'Operational Manager Email' );
  return $fields;
}

我甚至尝试按照URL来触发Jenkins通过命令行工作,但我只是一个初学者,我不明白。

我错过了这里的一切。对此有任何建议会有所帮助。任何有效的例子都会很棒。提前谢谢。

2 个答案:

答案 0 :(得分:0)

您必须传递下面列出的属性,并在Jenkins配置中进行配置更改。 在“触发远程构建”选项的Jenkins配置中设置具有某些值的令牌,并在Jenkins URL的查询参数中使用该值

connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
connection.setRequestProperty("Accept-Language", "en-US");
connection.setRequestProperty("Accept-Encoding", "gzip, deflate");

enter image description here

答案 1 :(得分:0)

Following code working as expected:

 try {
            URL url = new URL("http://localhost:8080/job/TestPrj/build"); // Jenkins URL localhost:8080, job named 'test'
            String user = "username"; // username
            String pass = "jenkinsapitoken"; // 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();
        }