下面列出了怎么用org.apache.commons.httpclient.UsernamePasswordCredentials的API类实例代码及写法,或者点击链接到github查看源代码。
public static void setNTLMCredentials(HttpClient httpClient, UsernamePasswordCredentials credentials,
String domain) {
initNTLMv2();
String localHostName;
try {
localHostName = Inet4Address.getLocalHost().getHostName();
} catch (Exception e) {
localHostName = "";
}
AuthScope authscope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
httpClient.getState().setCredentials(
authscope,
new NTCredentials(
credentials.getUserName(),
credentials.getPassword(),
localHostName, domain));
}
private void checkCredentials(String user, String password) {
try {
Pair<String, Integer> hostAndPort = UriUtils.validateUrl(downloadUrl);
if ((user != null) && (password != null)) {
client.getParams().setAuthenticationPreemptive(true);
Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
client.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
} else {
s_logger.info("No credentials configured for host=" + hostAndPort.first() + ":" + hostAndPort.second());
}
} catch (IllegalArgumentException iae) {
errorString = iae.getMessage();
status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
inited = false;
}
}
public void testAddRequest() throws Exception
{
AuthenticatedUrl url = new AuthenticatedUrl(this.getJrpipUrl(), new UsernamePasswordCredentials("username"));
HttpMessageTransport transport = new HttpMessageTransport();
Cookie cookie1 = new Cookie("domain", "cookie1", "val1", "/", 1000, false);
Cookie cookie2 = new Cookie("domain", "cookie2", "val2", "/", 1000, false);
Cookie cookie3 = new Cookie("domain", "cookie3", "val3", "/", 1000, false);
ThankYouWriter thankYouWriter = ThankYouWriter.getINSTANCE();
thankYouWriter.stopThankYouThread();
thankYouWriter.addRequest(transport, new HttpMessageTransportData(url, true, 0, new Cookie[]{cookie1, cookie2, cookie3}),
new RequestId(1));
thankYouWriter.addRequest(transport, new HttpMessageTransportData(url, true, 0, new Cookie[]{cookie1, cookie2, cookie3}),
new RequestId(2)); // same combination
thankYouWriter.addRequest(transport, new HttpMessageTransportData(url, true, 0, new Cookie[]{cookie3, cookie2, cookie1}),
new RequestId(3)); // cookie order changed
thankYouWriter.addRequest(transport, new HttpMessageTransportData(url, true, 0, new Cookie[]{cookie3}),
new RequestId(4)); // mismatch cookies
thankYouWriter.addRequest(transport, new HttpMessageTransportData(url, true, 0, new Cookie[]{}),
new RequestId(5)); // no cookies
thankYouWriter.addRequest(transport, new HttpMessageTransportData(url, true, 0, null)
, new RequestId(6)); // null cookies
assertEquals(3, thankYouWriter.getPendingRequests());
}
public HttpClient getHttpClient() {
String proxyUrl = System.getProperty("http.proxyHost");
String proxyPort = System.getProperty("http.proxyPort");
String proxyUser = System.getProperty("http.proxyUsername");
String proxyPassword = System.getProperty("http.proxyPassword");
HttpClient client = new HttpClient();
if (proxyUrl != null && proxyPort != null) {
logger.debug("Setting proxy configuration ...");
client.getHostConfiguration().setProxy(proxyUrl, Integer.parseInt(proxyPort));
if (proxyUser != null) {
logger.debug("Setting proxy authentication configuration ...");
HttpState state = new HttpState();
state.setProxyCredentials(null, null, new UsernamePasswordCredentials(proxyUser, proxyPassword));
client.setState(state);
}
} else {
logger.debug("No proxy configuration found");
}
return client;
}
private String getUserIdInWebModeWithoutSSO(HttpServletRequest httpRequest) {
UsernamePasswordCredentials credentials = this.findUserCredentials(httpRequest);
if (credentials != null) {
logger.debug("User credentials found.");
if (!httpRequest.getMethod().equalsIgnoreCase("POST")) {
logger.error("Request method is not POST!!!");
throw new InvalidMethodException();
}
logger.debug("Authenticating user ...");
try {
this.authenticate(credentials);
logger.debug("User authenticated");
httpRequest.getSession().setAttribute(SsoServiceInterface.SILENT_LOGIN, Boolean.TRUE);
} catch (Throwable t) {
logger.error("Authentication failed", t);
throw new SilentAuthenticationFailedException();
}
} else {
logger.debug("User credentials not found.");
}
String userId = credentials != null ? credentials.getUserName() : null;
return userId;
}
private void authenticate(UsernamePasswordCredentials credentials) throws Throwable {
logger.debug("IN: userId = " + credentials.getUserName());
try {
ISecurityServiceSupplier supplier = SecurityServiceSupplierFactory.createISecurityServiceSupplier();
SpagoBIUserProfile profile = supplier.checkAuthentication(credentials.getUserName(), credentials.getPassword());
if (profile == null) {
logger.error("Authentication failed for user " + credentials.getUserName());
throw new SecurityException("Authentication failed");
}
} catch (Throwable t) {
logger.error("Error while authenticating userId = " + credentials.getUserName(), t);
throw t;
} finally {
logger.debug("OUT");
}
}
private HttpClient getHttpClient() {
HttpClient client = new HttpClient();
Jenkins jenkins = Jenkins.getInstance();
if (jenkins != null) {
ProxyConfiguration proxy = jenkins.proxy;
if (proxy != null) {
client.getHostConfiguration().setProxy(proxy.name, proxy.port);
String username = proxy.getUserName();
String password = proxy.getPassword();
// Consider it to be passed if username specified. Sufficient?
if (StringUtils.isNotBlank(username)) {
client.getState().setProxyCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
}
}
}
client.getParams().setConnectionManagerTimeout(timeout);
client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
return client;
}
public static InputStream getInputStreamFromUrl(final String url, final String user, final String password) {
try {
final Pair<String, Integer> hostAndPort = validateUrl(url);
final HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());
if ((user != null) && (password != null)) {
httpclient.getParams().setAuthenticationPreemptive(true);
final Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
}
// Execute the method.
final GetMethod method = new GetMethod(url);
final int statusCode = httpclient.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
s_logger.error("Failed to read from URL: " + url);
return null;
}
return method.getResponseBodyAsStream();
} catch (final Exception ex) {
s_logger.error("Failed to read from URL: " + url);
return null;
}
}
/**
* Retrieves the content under the given URL with username and passwort
* authentication.
*
* @param url
* @param username
* @param password
* @return
* @throws IOException
*/
private static byte[] getUrlContent(URL url, String username,
String password) throws IOException {
final HttpClient client = new HttpClient();
// Set credentials:
client.getParams().setAuthenticationPreemptive(true);
final Credentials credentials = new UsernamePasswordCredentials(
username, password);
client.getState()
.setCredentials(
new AuthScope(url.getHost(), url.getPort(),
AuthScope.ANY_REALM), credentials);
// Retrieve content:
final GetMethod method = new GetMethod(url.toString());
final int status = client.executeMethod(method);
if (status != HttpStatus.SC_OK) {
throw new IOException("Error " + status + " while retrieving "
+ url);
}
return method.getResponseBody();
}
@Test
public void createClient() throws Exception {
// given
System.setProperty(HTTPS_PROXY_HOST, HTTPS_PROXY_HOST_VALUE);
System.setProperty(HTTPS_PROXY_PORT, HTTPS_PROXY_PORT_VALUE);
System.setProperty(HTTPS_PROXY_USER, HTTPS_PROXY_USER_VALUE);
System.setProperty(HTTPS_PROXY_PASSWORD, HTTPS_PROXY_PASSWORD_VALUE);
Credentials proxyCredentials = new UsernamePasswordCredentials(
HTTPS_PROXY_USER_VALUE, HTTPS_PROXY_PASSWORD_VALUE);
AuthScope authScope = new AuthScope(HTTPS_PROXY_HOST_VALUE,
Integer.parseInt(HTTPS_PROXY_PORT_VALUE));
// when
HttpClient client = vdcClient.createHttpClient();
// then
assertEquals(HTTPS_PROXY_HOST_VALUE, client.getHostConfiguration()
.getProxyHost());
assertEquals(HTTPS_PROXY_PORT_VALUE,
String.valueOf(client.getHostConfiguration().getProxyPort()));
assertEquals(proxyCredentials,
client.getState().getProxyCredentials(authScope));
}
/**
* Retrieves the content under the given URL with username and passwort
* authentication.
*
* @param url
* the URL to read
* @param username
* @param password
* @return the read content.
* @throws IOException
* if an I/O exception occurs.
*/
private static byte[] getUrlContent(URL url, String username,
String password) throws IOException {
final HttpClient client = new HttpClient();
// Set credentials:
client.getParams().setAuthenticationPreemptive(true);
final Credentials credentials = new UsernamePasswordCredentials(
username, password);
client.getState()
.setCredentials(
new AuthScope(url.getHost(), url.getPort(),
AuthScope.ANY_REALM), credentials);
// Retrieve content:
final GetMethod method = new GetMethod(url.toString());
final int status = client.executeMethod(method);
if (status != HttpStatus.SC_OK) {
throw new IOException("Error " + status + " while retrieving "
+ url);
}
return method.getResponseBody();
}
/**
* Returns a basic <tt>Authorization</tt> header value for the given
* {@link UsernamePasswordCredentials} and charset.
*
* @param credentials The credentials to encode.
* @param charset The charset to use for encoding the credentials
*
* @return a basic authorization string
*
* @since 3.0
*/
public static String authenticate(UsernamePasswordCredentials credentials, String charset) {
LOG.trace("enter BasicScheme.authenticate(UsernamePasswordCredentials, String)");
if (credentials == null) {
throw new IllegalArgumentException("Credentials may not be null");
}
if (charset == null || charset.length() == 0) {
throw new IllegalArgumentException("charset may not be null or empty");
}
StringBuffer buffer = new StringBuffer();
buffer.append(credentials.getUserName());
buffer.append(":");
buffer.append(credentials.getPassword());
return "Basic " + EncodingUtil.getAsciiString(
Base64.encodeBase64(EncodingUtil.getBytes(buffer.toString(), charset)));
}
public String sendReport(Map<String, String> values) throws IOException {
HttpClient httpClient = new HttpClient();
HostConfiguration hostConfiguration = new HostConfiguration();
if (!StringUtils.isBlank(proxy)) {
hostConfiguration.setProxy(proxy, proxyPort);
if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password)) {
httpClient.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
}
}
httpClient.setHostConfiguration(hostConfiguration);
PostMethod method = new PostMethod(getSendUrl());
addHttpPostParams(values, method);
int executeMethod = httpClient.executeMethod(method);
LOGGER.info("HTTP result of report send POST: " + executeMethod);
return IOUtils.toString(method.getResponseBodyAsStream());
}
/**
* A HttpClient with basic authentication and no host or port setting. Can only be used to retrieve absolute URLs
*
* @param user
* can be NULL
* @param password
* can be NULL
* @return HttpClient
*/
public static HttpClient getHttpClientInstance(String user, String password) {
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionParams params = connectionManager.getParams();
// wait max 10 seconds to establish connection
params.setConnectionTimeout(10000);
// a read() call on the InputStream associated with this Socket
// will block for only this amount
params.setSoTimeout(10000);
HttpClient c = new HttpClient(connectionManager);
// use basic authentication if available
if (user != null && user.length() > 0) {
AuthScope authScope = new AuthScope(null, -1, null);
Credentials credentials = new UsernamePasswordCredentials(user, password);
c.getState().setCredentials(authScope, credentials);
}
return c;
}
/**
* A HttpClient with basic authentication and no host or port setting. Can only be used to retrieve absolute URLs
*
* @param user
* can be NULL
* @param password
* can be NULL
* @return HttpClient
*/
public static HttpClient getHttpClientInstance(String user, String password) {
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionParams params = connectionManager.getParams();
// wait max 10 seconds to establish connection
params.setConnectionTimeout(10000);
// a read() call on the InputStream associated with this Socket
// will block for only this amount
params.setSoTimeout(10000);
HttpClient c = new HttpClient(connectionManager);
// use basic authentication if available
if (user != null && user.length() > 0) {
AuthScope authScope = new AuthScope(null, -1, null);
Credentials credentials = new UsernamePasswordCredentials(user, password);
c.getState().setCredentials(authScope, credentials);
}
return c;
}
private Socket AuthenticateProxy(ConnectMethod method, ProxyClient client,
String proxyHost, int proxyPort,
String proxyUsername, String proxyPassword) throws IOException {
if(method.getProxyAuthState().getAuthScheme().getSchemeName().equalsIgnoreCase("ntlm")) {
// If Auth scheme is NTLM, set NT credentials with blank host and domain name
client.getState().setProxyCredentials(new AuthScope(proxyHost, proxyPort),
new NTCredentials(proxyUsername, proxyPassword,"",""));
} else {
// If Auth scheme is Basic/Digest, set regular Credentials
client.getState().setProxyCredentials(new AuthScope(proxyHost, proxyPort),
new UsernamePasswordCredentials(proxyUsername, proxyPassword));
}
ProxyClient.ConnectResponse response = client.connect();
Socket socket = response.getSocket();
if (socket == null) {
method = response.getConnectMethod();
throw new ProtocolException("Proxy Authentication failed. Socket not created: "
+ method.getStatusLine());
}
return socket;
}
public static InputStream getInputStreamFromUrl(String url, String user, String password) {
try {
Pair<String, Integer> hostAndPort = validateUrl(url);
HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());
if ((user != null) && (password != null)) {
httpclient.getParams().setAuthenticationPreemptive(true);
Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
}
// Execute the method.
GetMethod method = new GetMethod(url);
int statusCode = httpclient.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
s_logger.error("Failed to read from URL: " + url);
return null;
}
return method.getResponseBodyAsStream();
} catch (Exception ex) {
s_logger.error("Failed to read from URL: " + url);
return null;
}
}
/**
* Extracts username and password from the given <code>url</code>. A valid
* url to extract {@link Credentials} from looks like:
*
* <pre>
* http://username:[email protected]
* </pre>
*
* @param url the URL to extract {@link Credentials} from
*
* @return the exracted Credentials or <code>null</code> if the given
* <code>url</code> does not contain credentials
*/
protected static Credentials extractCredentials(String url) {
Matcher matcher = URL_CREDENTIALS_PATTERN.matcher(url);
if (matcher.matches()) {
matcher.reset();
String username = "";
String password = "";
while (matcher.find()) {
username = matcher.group(1);
password = matcher.group(2);
}
Credentials credentials = new UsernamePasswordCredentials(username, password);
return credentials;
}
return null;
}
public void init()
{
ParameterCheck.mandatory("baseUrl", baseUrl);
StringBuilder sb = new StringBuilder();
sb.append(baseUrl + "/admin/cores");
this.adminUrl = sb.toString();
httpClient = httpClientFactory.getHttpClient();
HttpClientParams params = httpClient.getParams();
params.setBooleanParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, true);
httpClient.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials("admin", "admin"));
}
/**
* Returns the Ticket in the form used for HTTP Basic Authentication.
* This should be added as the value to a HTTP Request Header with
* key Authorization
*/
public String getAsHTTPAuthorization()
{
// Build from the Username and Password
Pair<String,String> userPass = getAsUsernameAndPassword();
Credentials credentials = new UsernamePasswordCredentials(userPass.getFirst(), userPass.getSecond());
// Encode it into the required format
String credentialsEncoded = Base64.encodeBytes(
credentials.toString().getBytes(utf8), Base64.DONT_BREAK_LINES );
// Mark it as Basic, and we're done
return "Basic " + credentialsEncoded;
}
@Override
protected void setUp() throws Exception
{
super.setUp();
if (remoteServer != null)
{
httpClient = new HttpClient();
httpClient.getParams().setBooleanParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, true);
if (remoteServer.username != null)
{
httpClient.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(remoteServer.username, remoteServer.password));
}
}
}
/**
* Builds an HTTP client with the given settings. Settings are NOT reset to their default values after a client has
* been created.
*
* @return the created client.
*/
public HttpClient buildClient() {
if (httpsProtocolSocketFactory != null) {
Protocol.registerProtocol("https", new Protocol("https", httpsProtocolSocketFactory, 443));
}
HttpClientParams clientParams = new HttpClientParams();
clientParams.setAuthenticationPreemptive(isPreemptiveAuthentication());
clientParams.setContentCharset(getContentCharSet());
clientParams.setParameter(HttpClientParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(
connectionRetryAttempts, false));
HttpConnectionManagerParams connMgrParams = new HttpConnectionManagerParams();
connMgrParams.setConnectionTimeout(getConnectionTimeout());
connMgrParams.setDefaultMaxConnectionsPerHost(getMaxConnectionsPerHost());
connMgrParams.setMaxTotalConnections(getMaxTotalConnections());
connMgrParams.setReceiveBufferSize(getReceiveBufferSize());
connMgrParams.setSendBufferSize(getSendBufferSize());
connMgrParams.setTcpNoDelay(isTcpNoDelay());
MultiThreadedHttpConnectionManager connMgr = new MultiThreadedHttpConnectionManager();
connMgr.setParams(connMgrParams);
HttpClient httpClient = new HttpClient(clientParams, connMgr);
if (proxyHost != null) {
HostConfiguration hostConfig = new HostConfiguration();
hostConfig.setProxy(proxyHost, proxyPort);
httpClient.setHostConfiguration(hostConfig);
if (proxyUsername != null) {
AuthScope proxyAuthScope = new AuthScope(proxyHost, proxyPort);
UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(proxyUsername,
proxyPassword);
httpClient.getState().setProxyCredentials(proxyAuthScope, proxyCredentials);
}
}
return httpClient;
}
/**
* Sets the username and password used to access the metadata URL. To disable BASIC authentication set the username
* and password to null;
*
* @param username the username
* @param password the password
*/
public void setBasicCredentials(String username, String password) {
if (username == null && password == null) {
httpClient.getState().setCredentials(null, null);
} else {
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
httpClient.getState().setCredentials(authScope, credentials);
}
}
@SuppressWarnings("deprecation")
public String getAccessToken() {
if (this.oAuth2AccessToken != null) {
return this.oAuth2AccessToken;
}
try {
HttpClient client = new HttpClient();
client.getParams().setAuthenticationPreemptive(true);
Credentials defaultcreds = new UsernamePasswordCredentials(this.getUsername(), this.getPassword());
client.getState().setCredentials(AuthScope.ANY, defaultcreds);
PostMethod method = new PostMethod(this.getOAuthAuthorizationServer());
method.setRequestBody("grant_type=client_credentials");
int responseCode = client.executeMethod(method);
if (responseCode != 200) {
throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer()
+ ", got response code " + responseCode);
}
String responseBody = method.getResponseBodyAsString();
JSONObject accessResponse = new JSONObject(responseBody);
accessResponse.getString("access_token");
return (this.oAuth2AccessToken = accessResponse.getString("access_token"));
} catch (Exception e) {
throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e);
}
}
/**
* @param proxy
* @param httpClient
*/
public static void setProxy(final Proxy proxy, final HttpClient httpClient) {
if (proxy != null && httpClient != null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Setting proxy with host " + proxy.getHost() + " and port " + proxy.getPort() + " for host " + httpClient.getHostConfiguration().getHost() + ":" +
httpClient.getHostConfiguration().getPort());
}
httpClient.getHostConfiguration().setProxy(proxy.getHost(), proxy.getPort());
if (proxy.getUserName() != null && proxy.getPassword() != null) {
httpClient.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxy.getUserName(), proxy.getPassword()));
}
}
}
/**
* @param username
* @param password
* @param httpClient
*/
public static void setCredentials(final String username, final String password, final HttpClient httpClient) {
if (username != null && password != null && httpClient != null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Setting credentials with username " + username + " for host " + httpClient.getHostConfiguration().getHost() + ":" + httpClient.getHostConfiguration
().getPort());
}
httpClient.getParams().setAuthenticationPreemptive(true);
httpClient.getState().setCredentials(
new AuthScope(httpClient.getHostConfiguration().getHost(), httpClient.getHostConfiguration().getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials
(username, password));
}
}
public HttpClient createHttpClient() {
HttpClient client = new HttpClient();
String proxyHost = System.getProperty(HTTPS_PROXY_HOST);
String proxyPort = System.getProperty(HTTPS_PROXY_PORT);
String proxyUser = System.getProperty(HTTPS_PROXY_USER);
String proxyPassword = System.getProperty(HTTPS_PROXY_PASSWORD);
int proxyPortInt = 0;
try {
proxyPortInt = Integer.parseInt(proxyPort);
} catch (NumberFormatException e) {
// ignore
}
if (!useProxyByPass(this.apiUrl)) {
if (proxyHost != null && proxyPortInt > 0) {
client.getHostConfiguration().setProxy(proxyHost, proxyPortInt);
if (proxyUser != null && proxyUser.length() > 0
&& proxyPassword != null && proxyPassword.length() > 0) {
HttpState state = new HttpState();
Credentials proxyCredentials = new UsernamePasswordCredentials(
proxyUser, proxyPassword);
state.setProxyCredentials(new AuthScope(proxyHost,
proxyPortInt), proxyCredentials);
client.setState(state);
}
}
}
return client;
}
protected Confluence(String endpoint, ConfluenceProxy proxyInfo ) throws URISyntaxException, MalformedURLException {
this(new XmlRpcClient());
if (endpoint.endsWith("/")) {
endpoint = endpoint.substring(0, endpoint.length() - 1);
}
endpoint = ConfluenceService.Protocol.XMLRPC.addTo(endpoint);
final java.net.URI serviceURI = new java.net.URI(endpoint);
XmlRpcClientConfigImpl clientConfig = new XmlRpcClientConfigImpl();
clientConfig.setServerURL(serviceURI.toURL() );
clientConfig.setEnabledForExtensions(true); // add this to support attachment upload
client.setConfig( clientConfig );
if( isProxyEnabled(proxyInfo, serviceURI) ) {
final XmlRpcCommonsTransportFactory transportFactory = new XmlRpcCommonsTransportFactory( client );
final HttpClient httpClient = new HttpClient();
final HostConfiguration hostConfiguration = httpClient.getHostConfiguration();
hostConfiguration.setProxy( proxyInfo.host, proxyInfo.port );
hostConfiguration.setHost(serviceURI.getHost(), serviceURI.getPort(), serviceURI.toURL().getProtocol());
if( !isNullOrEmpty(proxyInfo.userName) && !isNullOrEmpty(proxyInfo.password) ) {
Credentials cred = new UsernamePasswordCredentials(proxyInfo.userName,proxyInfo.password);
httpClient.getState().setProxyCredentials(AuthScope.ANY, cred);
}
transportFactory.setHttpClient( httpClient );
client.setTransportFactory( transportFactory );
}
}
private static boolean doAuthenticateDefault(
HttpMethod method,
HttpConnection conn,
HttpState state,
boolean proxy)
throws AuthenticationException {
if (method == null) {
throw new IllegalArgumentException("HTTP method may not be null");
}
if (state == null) {
throw new IllegalArgumentException("HTTP state may not be null");
}
String host = null;
if (conn != null) {
host = proxy ? conn.getProxyHost() : conn.getHost();
}
Credentials credentials = proxy
? state.getProxyCredentials(null, host) : state.getCredentials(null, host);
if (credentials == null) {
return false;
}
if (!(credentials instanceof UsernamePasswordCredentials)) {
throw new InvalidCredentialsException(
"Credentials cannot be used for basic authentication: "
+ credentials.toString());
}
String auth = BasicScheme.authenticate(
(UsernamePasswordCredentials) credentials,
method.getParams().getCredentialCharset());
if (auth != null) {
String s = proxy ? PROXY_AUTH_RESP : WWW_AUTH_RESP;
Header header = new Header(s, auth, true);
method.addRequestHeader(header);
return true;
} else {
return false;
}
}
private void init(String host, int port, String userName, String password) {
this.host = host;
this.port = port;
this.userName = userName;
this.password = password;
this.baseUrl = "http://" + host + ":" + port + "/kylin/api";
client = new HttpClient();
if (userName != null && password != null) {
client.getParams().setAuthenticationPreemptive(true);
Credentials creds = new UsernamePasswordCredentials(userName, password);
client.getState().setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), creds);
}
}