当前位置: 首页>>代码示例>>Java>>正文


Java Authenticator.setDefault方法代码示例

本文整理汇总了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);
  }
}
 
开发者ID:oncewang,项目名称:oryx2,代码行数:21,代码来源:SecureAPIConfigIT.java

示例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;
    }
 
开发者ID:epam,项目名称:NGB,代码行数:23,代码来源:HttpDataManager.java

示例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"));
}
 
开发者ID:lizhangqu,项目名称:PriorityOkHttp,代码行数:21,代码来源:HttpOverSpdyTest.java

示例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 );
	}		
	
}
 
开发者ID:markkolich,项目名称:axisviewer,代码行数:33,代码来源:Camera.java

示例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());
    }
}
 
开发者ID:kraftek,项目名称:awsdownload,代码行数:18,代码来源:NetUtils.java

示例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;
        }
    });
}
 
开发者ID:WASdev,项目名称:tool.lars,代码行数:25,代码来源:ProxyTest.java

示例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;
    }
}
 
开发者ID:webmate-io,项目名称:webmate-jenkins-plugin,代码行数:30,代码来源:WebmateXBrowserBuilder.java

示例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;
}
 
开发者ID:microcks,项目名称:microcks,代码行数:28,代码来源:ImportServiceDefinitionTask.java

示例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;
}
 
开发者ID:kwin,项目名称:cppcheclipse,代码行数:21,代码来源:HttpClientService.java

示例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);
	}

    }
 
开发者ID:kawansoft,项目名称:aceql-http,代码行数:30,代码来源:AceQLHttpApi.java

示例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();
  }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:14,代码来源:URLConnectionTest.java

示例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"));
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:34,代码来源:URLConnectionTest.java

示例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());
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:33,代码来源:URLConnectionTest.java

示例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();
}
 
开发者ID:marlonwang,项目名称:raven,代码行数:15,代码来源:NativeHttpClient.java

示例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());
  }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:37,代码来源:URLConnectionTest.java


注:本文中的java.net.Authenticator.setDefault方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。