下载Build Authorization Token Root Plugin插件
下载 Strict Crumb Issuer Plugin 插件
因为高版本Jenkins认为跨域不安全,只能用这个插件来访问允许跨域的XAPI
修改安全配置
Jenkins Manager -> Configure Global Security
打开匿名阅读访问
设置关闭 Session ID
这里切换成 Strict Crumb Issuer 如何打开项目任务?Java代码(国外一个哥哥写的,直接搬轮子用) 简单的说下
package ;/** * @description: TODO * @author zhoukai * @date 2022/7/25 15:50 * @version 1.0 */ import org.apache.http.auth.*; import org.apache.http.client.*; import org.apache.http.client.methods.*; import org.apache.http.impl.client.*; import com.google.gson.Gson; public class JenkinsMonitor {
public static void main(String[] args) throws Exception {
String protocol = "http"; String host = "10.128.22.132"; int port = 4898; String usernName = "admin"; String password = "xxx@123"; DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getCredetialsProvider().setCredentials(
new AuthScope(host, port),
new UsernamePasswordCredentials(usernName, password));
String jenkinsUrl = protocol + "://" + host + ":" + port;
try {
// get the crumb from Jenkins
// do this only once per HTTP session
// keep the crumb for every coming request
System.out.println("... issue crumb");
HttpGet httpGet = new HttpGet(jenkinsUrl + "/crumbIssuer/api/json");
String crumbResponse= toString(httpclient, httpGet);
CrumbJson crumbJson = new Gson()
.fromJson(crumbResponse, CrumbJson.class);
System.err.println("接收登录返回?");
System.err.println(crumbJson);
// add the issued crumb to each request header
// the header field name is also contained in the json response
System.out.println("... issue rss of latest builds");
HttpPost httpost = new HttpPost(jenkinsUrl + "/job/test_op/buildWithParameters?token=110a00fc92994e0b711d3370ee193ef4be&BRANCH=123"); //这里的URL根据需求改.我这里使用了Parameter插件了,所以传入一个参数
// httpost.addHeader("token","110a00fc92994e0b711d3370ee193ef4be");
httpost.addHeader(crumbJson.crumbRequestField, crumbJson.crumb);
toString(httpclient, httpost);
} finally {
httpclient.getConnectionManager().shutdown();
}
}
// helper construct to deserialize crumb json into
public static class CrumbJson {
public String crumb;
public String crumbRequestField;
@Override
public String toString() {
return "CrumbJson{" +
"crumb='" + crumb + '\'' +
", crumbRequestField='" + crumbRequestField + '\'' +
'}';
}
}
private static String toString(DefaultHttpClient client,
HttpRequestBase request) throws Exception {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = client.execute(request, responseHandler);
System.out.println(responseBody + "\n");
return responseBody;
}
}