HttpClient java.net.UnknownHostException CURL 命令通过时出现异常

HttpClient java.net.UnknownHostException exception when the CURL command passes

我正在尝试使用 httpclient 调用 Jenkins 以获取作业列表。

当我 运行 我的代码时,我得到一个 UnknownHostException

我尝试使用 curl 发出相同的请求并且我能够得到结果。我不确定如何解释这个。

void nwe() throws ClientProtocolException, IOException {
    HttpHost target = new HttpHost("https://<JENKINS_URL>/api");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    HttpGet httpGet = new HttpGet("/json");
    httpGet.setHeader("Content-type", "application/json");
    BasicScheme basicAuth = new BasicScheme();
    HttpClientContext localContext = HttpClientContext.create();
    CloseableHttpResponse response1 = httpclient.execute(target, httpGet, localContext);
    System.out.println(response1.getStatusLine());

}

同一个 URL 上的 CURL 命令给出了预期的输出

谢谢, 阿马尔

阅读 JavaDoc for HttpHost:

Parameters: hostname - the hostname (IP or DNS name)

所以你应该只使用(省略协议和上下文):

HttpHost target = new HttpHost( "<JENKINS_URL>" );

然后 HttpGet /api/json 部分。

干杯,