如何使用 Java 远程登录到 Jenkins 服务器?

How to remotely login to a Jenkins server using Java?

我正在尝试使用 Java 远程登录到 Jenkins 服务器。

我没有找到有关如何安全完成此操作的文档。

对于使用 url 的本地服务器:http://user:pass@server 不起作用。

谁能给我推荐一些关于这个主题的文档?

文档来自 jenkins wiki

应该适用于您的基本身份验证类型。

Java 示例与 httpclient 4.3.x

import java.io.IOException;
import java.net.URI;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class JenkinsScraper {

    public String scrape(String urlString, String username, String password) throws ClientProtocolException, IOException {
        URI uri = URI.create(urlString);
        HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(username, password));
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        HttpGet httpGet = new HttpGet(uri);
        // Add AuthCache to the execution context
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        HttpResponse response = httpClient.execute(host, httpGet, localContext);

        return EntityUtils.toString(response.getEntity());
    }

}

Http/Html方式最麻烦!我会使用 jenkins cli 或远程 api。如果您仍然坚持将 Java 与 http 一起使用,那么您需要使用基本的 http 身份验证,如果您计划在 jenkins 中触发更多步骤,请使用适当的 Http/Html Java 库,例如 Java-Selenium 或 HttpUnit。

在 Java 中使用 http basic auth 的最佳简单解决方案我在这里找到: