2015-07-10 73 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?

相關問題