2015-07-10 119 views

回答

1

机制的文档应该与你的基本身份验证类型的工作。

与HttpClient的4.3.x版的Java例子

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()); 
    } 

} 
+0

我的问题实际上与安全有关,可以直接从用户发送密码到UsernamePasswordCredentials而不加密吗? –

+0

那么如果它比编程更安全的问题,我不会推荐使用http和基本身份验证的远程登录。在到达主机之前,我更喜欢前面的某种安全性,一些vpn或ssh隧道。 – MrSimpleMind

+0

通过http发送它将允许您的网络中的任何人捕获密码,它是纯文本并且易于抓取。如上所述,我不会打开我的服务器进行公共或远程登录。但使用安全的Vpn或ssh隧道或...将使其更安全。 – MrSimpleMind

1

的HTTP/HTML的方式是最麻烦的!我会使用jenkins cli或远程API。如果你仍然坚持用http来使用Java,那么你需要使用基本的http认证,如果你计划触发jenkins中的更多步骤,使用适当的Http/Html Java库,比如Java-Selenium或HttpUnit。

最佳和使用简单的解决方案HTTP在Java中基本身份验证我发现这里: Http Basic Authentication in Java using HttpClient?

相关问题