本文整理匯總了Java中java.net.Authenticator.setDefault方法的典型用法代碼示例。如果您正苦於以下問題:Java Authenticator.setDefault方法的具體用法?Java Authenticator.setDefault怎麽用?Java Authenticator.setDefault使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.net.Authenticator
的用法示例。
在下文中一共展示了Authenticator.setDefault方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: testUserPassword
import java.net.Authenticator; //導入方法依賴的package包/類
@Test
public void testUserPassword() throws Exception {
startServer(buildUserPasswordConfig());
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("oryx", "pass".toCharArray());
}
});
try {
String response = Resources.toString(
new URL("http://localhost:" + getHTTPPort() + "/helloWorld"),
StandardCharsets.UTF_8);
assertEquals("Hello, World", response);
} finally {
Authenticator.setDefault(null);
}
}
示例2: createConnection
import java.net.Authenticator; //導入方法依賴的package包/類
private HttpURLConnection createConnection(final String location) throws IOException {
URL url = new URL(location);
HttpURLConnection conn;
if (proxyHost != null && proxyPort != null) {
if (proxyUser != null && proxyPassword != null) {
Authenticator authenticator = new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
}
};
Authenticator.setDefault(authenticator);
}
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
conn = (HttpURLConnection) url.openConnection(proxy);
} else {
conn = (HttpURLConnection) url.openConnection();
}
return conn;
}
示例3: authenticate
import java.net.Authenticator; //導入方法依賴的package包/類
@Test public void authenticate() throws Exception {
server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_UNAUTHORIZED)
.addHeader("www-authenticate: Basic realm=\"protected area\"")
.setBody("Please authenticate."));
server.enqueue(new MockResponse().setBody("Successful auth!"));
Authenticator.setDefault(new RecordingAuthenticator());
urlFactory.setClient(urlFactory.client().newBuilder()
.authenticator(new JavaNetAuthenticator())
.build());
connection = urlFactory.open(server.url("/").url());
assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
RecordedRequest denied = server.takeRequest();
assertNull(denied.getHeader("Authorization"));
RecordedRequest accepted = server.takeRequest();
assertEquals("GET / HTTP/1.1", accepted.getRequestLine());
assertEquals("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS,
accepted.getHeader("Authorization"));
}
示例4: Camera
import java.net.Authenticator; //導入方法依賴的package包/類
/**
* Create a new Camera object.
* @param name
* @param url
* @param username
* @param password
* @param refreshRate
*/
public Camera ( String name, String url, String username, String password, long refreshRate ) {
this.cameraName = name; // Set the camera name.
this.cameraURLString = url; // Set the camera URL.
this.username = username; // Set the camera username.
this.password = password; // Set the camera password.
this.refreshRate = refreshRate; // Set the desired refresh rate.
try {
// Create a new URL object from the URL-string of our camera.
cameraURL = new URL( this.cameraURLString );
}
catch( MalformedURLException m ) {
this.error = true;
}
// Check if this camera requires authentication.
// If so, then create and set the authenticator object.
if ( !username.equals("") && !password.equals("") ) {
this.authenticator = new MyAuthenticator( this.username, this.password );
Authenticator.setDefault( this.authenticator );
}
}
示例5: setProxy
import java.net.Authenticator; //導入方法依賴的package包/類
public static void setProxy(String type, final String host, final int port, final String user, final String pwd) {
if (type != null && host != null) {
Proxy.Type proxyType = Enum.valueOf(Proxy.Type.class, type.toUpperCase());
javaNetProxy = new Proxy(proxyType, new InetSocketAddress(host, port));
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pwd.toCharArray());
}
});
if (user != null && pwd != null) {
proxyCredentials = new BasicCredentialsProvider();
proxyCredentials.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(user, pwd));
}
apacheHttpProxy = new HttpHost(host, port, proxyType.name());
}
}
示例6: setAuthenticator
import java.net.Authenticator; //導入方法依賴的package包/類
/**
* Return the provided proxy userid and password on a call to the system Authenticator
*
* @param pUser
* @param pPwd
*/
private void setAuthenticator(final String pUser, final String pPwd) {
if (_verbose) {
logger.log(Level.INFO, "Authenticator set to return user=" + pUser + ", pwd=" + pPwd);
}
Authenticator.setDefault(new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
if (_verbose) {
logger.log(Level.INFO, "AUTHENTICATOR called for type=" + getRequestorType() + ", host=" + getRequestingHost() + ", port=" + getRequestingPort());
}
if (getRequestorType() == RequestorType.PROXY) {
return new PasswordAuthentication(pUser, pPwd.toCharArray());
}
return null;
}
});
}
示例7: getProxy
import java.net.Authenticator; //導入方法依賴的package包/類
/**
* Leverages Jenkins internal proxy configuration.
* @return
* <ul>
* <li><b>null</b> : if no proxy is configured</li>
* <li>proxy host supporting standard authentification </li>
* </ul>
*/
private HttpHost getProxy() throws IOException {
ProxyConfiguration config = ProxyConfiguration.load();
if (config != null) {
if (config.getUserName() != null) {
// Add an authenticator which provides the credentials for proxy authentication
Authenticator.setDefault(new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType() != RequestorType.PROXY) return null;
ProxyConfiguration p = Jenkins.getInstance().proxy;
return new PasswordAuthentication(p.getUserName(),
p.getPassword().toCharArray());
}
});
}
return new HttpHost(config.name, config.port);
} else {
return null;
}
}
示例8: getRepositoryUrlEtag
import java.net.Authenticator; //導入方法依賴的package包/類
/**
* Extract URL Etag in order to avoid a reimport on unchanged resource.
* @param repositoryUrl The URL to test as
* @return The etag or null if none.
*/
private String getRepositoryUrlEtag(String repositoryUrl){
Authenticator.setDefault(new UsernamePasswordAuthenticator(username, password));
try{
URLConnection connection = new URL(repositoryUrl).openConnection();
// Try simple syntax.
String etag = connection.getHeaderField("Etag");
if (etag != null){
log.debug("Found an Etag for " + repositoryUrl + ": " + etag);
return etag;
}
// Try other syntax.
etag = connection.getHeaderField("ETag");
if (etag != null){
log.debug("Found an ETag for " + repositoryUrl + ": " + etag);
return etag;
}
} catch (Exception e){
log.error("Caught an exception while retrieving Etag for " + repositoryUrl, e);
}
log.debug("No Etag found for " + repositoryUrl + " !");
return null;
}
示例9: getProxyFromProxyData
import java.net.Authenticator; //導入方法依賴的package包/類
private Proxy getProxyFromProxyData(IProxyData proxyData) throws UnknownHostException {
Type proxyType;
if (IProxyData.HTTP_PROXY_TYPE.equals(proxyData.getType())) {
proxyType = Type.HTTP;
} else if (IProxyData.SOCKS_PROXY_TYPE.equals(proxyData.getType())) {
proxyType = Type.SOCKS;
} else if (IProxyData.HTTPS_PROXY_TYPE.equals(proxyData.getType())) {
proxyType = Type.HTTP;
} else {
throw new IllegalArgumentException("Invalid proxy type " + proxyData.getType());
}
InetSocketAddress sockAddr = new InetSocketAddress(InetAddress.getByName(proxyData.getHost()), proxyData.getPort());
Proxy proxy = new Proxy(proxyType, sockAddr);
if (!Strings.isNullOrEmpty(proxyData.getUserId())) {
Authenticator.setDefault(new ProxyAuthenticator(proxyData.getUserId(), proxyData.getPassword()));
}
return proxy;
}
示例10: setProxyCredentials
import java.net.Authenticator; //導入方法依賴的package包/類
private void setProxyCredentials() {
if (proxy == null) {
return;
}
// Sets the credential for authentication
if (passwordAuthentication != null) {
final String proxyAuthUsername = passwordAuthentication
.getUserName();
final char[] proxyPassword = passwordAuthentication.getPassword();
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(proxyAuthUsername,
proxyPassword);
}
};
if (DEBUG) {
System.out.println("passwordAuthentication: "
+ proxyAuthUsername + " " + new String(proxyPassword));
}
Authenticator.setDefault(authenticator);
}
}
示例11: tearDown
import java.net.Authenticator; //導入方法依賴的package包/類
@After public void tearDown() throws Exception {
Authenticator.setDefault(null);
System.clearProperty("proxyHost");
System.clearProperty("proxyPort");
System.clearProperty("http.agent");
System.clearProperty("http.proxyHost");
System.clearProperty("http.proxyPort");
System.clearProperty("https.proxyHost");
System.clearProperty("https.proxyPort");
if (cache != null) {
cache.delete();
}
}
示例12: proxyAuthenticateOnConnect
import java.net.Authenticator; //導入方法依賴的package包/類
@Test public void proxyAuthenticateOnConnect() throws Exception {
Authenticator.setDefault(new RecordingAuthenticator());
server.useHttps(sslClient.socketFactory, true);
server.enqueue(new MockResponse().setResponseCode(407)
.addHeader("Proxy-Authenticate: Basic realm=\"localhost\""));
server.enqueue(
new MockResponse().setSocketPolicy(UPGRADE_TO_SSL_AT_END).clearHeaders());
server.enqueue(new MockResponse().setBody("A"));
urlFactory.setClient(urlFactory.client().newBuilder()
.proxyAuthenticator(new JavaNetAuthenticator())
.proxy(server.toProxyAddress())
.sslSocketFactory(sslClient.socketFactory, sslClient.trustManager)
.hostnameVerifier(new RecordingHostnameVerifier())
.build());
URL url = new URL("https://android.com/foo");
connection = urlFactory.open(url);
assertContent("A", connection);
RecordedRequest connect1 = server.takeRequest();
assertEquals("CONNECT android.com:443 HTTP/1.1", connect1.getRequestLine());
assertNull(connect1.getHeader("Proxy-Authorization"));
RecordedRequest connect2 = server.takeRequest();
assertEquals("CONNECT android.com:443 HTTP/1.1", connect2.getRequestLine());
assertEquals("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS,
connect2.getHeader("Proxy-Authorization"));
RecordedRequest get = server.takeRequest();
assertEquals("GET /foo HTTP/1.1", get.getRequestLine());
assertNull(get.getHeader("Proxy-Authorization"));
}
示例13: testAuthenticateWithStreamingPost
import java.net.Authenticator; //導入方法依賴的package包/類
private void testAuthenticateWithStreamingPost(StreamingMode streamingMode) throws Exception {
MockResponse pleaseAuthenticate = new MockResponse().setResponseCode(401)
.addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
.setBody("Please authenticate.");
server.enqueue(pleaseAuthenticate);
Authenticator.setDefault(new RecordingAuthenticator());
urlFactory.setClient(urlFactory.client().newBuilder()
.authenticator(new JavaNetAuthenticator())
.build());
connection = urlFactory.open(server.url("/").url());
connection.setDoOutput(true);
byte[] requestBody = {'A', 'B', 'C', 'D'};
if (streamingMode == StreamingMode.FIXED_LENGTH) {
connection.setFixedLengthStreamingMode(requestBody.length);
} else if (streamingMode == StreamingMode.CHUNKED) {
connection.setChunkedStreamingMode(0);
}
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody);
outputStream.close();
try {
connection.getInputStream();
fail();
} catch (HttpRetryException expected) {
}
// no authorization header for the request...
RecordedRequest request = server.takeRequest();
assertNull(request.getHeader("Authorization"));
assertEquals("ABCD", request.getBody().readUtf8());
}
示例14: NativeHttpClient
import java.net.Authenticator; //導入方法依賴的package包/類
public NativeHttpClient(String authCode, int maxRetryTimes, HttpProxy proxy) {
this._maxRetryTimes = maxRetryTimes;
LOG.info("Created instance with _maxRetryTimes = " + _maxRetryTimes);
this._authCode = authCode;
this._proxy = proxy;
if ( null != _proxy && _proxy.isAuthenticationNeeded()) {
Authenticator.setDefault(new SimpleProxyAuthenticator(
_proxy.getUsername(), _proxy.getPassword()));
}
initSSL();
}
示例15: authenticateWithPost
import java.net.Authenticator; //導入方法依賴的package包/類
@Test public void authenticateWithPost() throws Exception {
MockResponse pleaseAuthenticate = new MockResponse().setResponseCode(401)
.addHeader("WWW-Authenticate: Basic realm=\"protected area\"")
.setBody("Please authenticate.");
// fail auth three times...
server.enqueue(pleaseAuthenticate);
server.enqueue(pleaseAuthenticate);
server.enqueue(pleaseAuthenticate);
// ...then succeed the fourth time
server.enqueue(new MockResponse().setBody("Successful auth!"));
Authenticator.setDefault(new RecordingAuthenticator());
urlFactory.setClient(urlFactory.client().newBuilder()
.authenticator(new JavaNetAuthenticator())
.build());
connection = urlFactory.open(server.url("/").url());
connection.setDoOutput(true);
byte[] requestBody = {'A', 'B', 'C', 'D'};
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody);
outputStream.close();
assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
// no authorization header for the first request...
RecordedRequest request = server.takeRequest();
assertNull(request.getHeader("Authorization"));
// ...but the three requests that follow include an authorization header
for (int i = 0; i < 3; i++) {
request = server.takeRequest();
assertEquals("POST / HTTP/1.1", request.getRequestLine());
assertEquals("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS,
request.getHeader("Authorization"));
assertEquals("ABCD", request.getBody().readUtf8());
}
}