List of usage examples for java.net ProxySelector getDefault
public static ProxySelector getDefault()
From source file:org.gradle.api.internal.artifacts.repositories.transport.http.HttpClientConfigurer.java
private void configureProxy(DefaultHttpClient httpClient, HttpProxySettings proxySettings) { // Use standard JVM proxy settings ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); HttpProxySettings.HttpProxy proxy = proxySettings.getProxy(); if (proxy != null && proxy.credentials != null) { useCredentials(httpClient, proxy.credentials, proxy.host, proxy.port); }/*from w ww. j a v a2s .c o m*/ }
From source file:com.globo.aclapi.client.ClientAclAPI.java
private static ApacheHttpTransport getTransport(int timeout, boolean verifySSL) throws RuntimeException { if (verifySSL) { return new ApacheHttpTransport(newDefaultHttpClient(SSLSocketFactory.getSocketFactory(), getHttpParams(timeout), ProxySelector.getDefault())); } else {/*www. j a v a2 s . com*/ try { SSLContext ctx = SSLContext.getInstance("SSL"); X509TrustManager tm = new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); return new ApacheHttpTransport( newDefaultHttpClient(ssf, getHttpParams(timeout), ProxySelector.getDefault())); } catch (Exception e) { throw new RuntimeException("ERRO ssl schema", e); } } }
From source file:com.okta.sdk.framework.ApiClient.java
/** * Constructor for the ApiClient.//from w w w . jav a 2s .c o m * * Bootstraps an HTTPClient to make various requests to the Okta API. * * @param config {@link ApiClientConfiguration} */ public ApiClient(ApiClientConfiguration config) { Proxy proxy = ProxySelector.getDefault().select(URI.create(config.getBaseUrl())).iterator().next(); HttpRoutePlanner routePlanner; if (Proxy.Type.HTTP.equals(proxy.type())) { URI proxyUri = URI.create(proxy.type() + "://" + proxy.address()); HttpHost proxyHost = new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme()); routePlanner = new DefaultProxyRoutePlanner(proxyHost); } else { routePlanner = new DefaultRoutePlanner(null); } StandardHttpRequestRetryHandler requestRetryHandler = new StandardHttpRequestRetryHandler(RETRY_COUNT, true); HttpClient client = HttpClientBuilder.create().setRetryHandler(requestRetryHandler) .setUserAgent("OktaSDKJava_v" + Utils.getSdkVersion()).disableCookieManagement() .setRoutePlanner(routePlanner).build(); this.httpClient = client; this.baseUrl = config.getBaseUrl(); this.apiVersion = config.getApiVersion(); this.configuration = config; this.token = config.getApiToken(); initMarshaller(); }
From source file:org.openqa.selenium.remote.internal.HttpClientFactory.java
public HttpRoutePlanner getRoutePlanner(SchemeRegistry registry) { return new ProxySelectorRoutePlanner(registry, ProxySelector.getDefault()); }
From source file:com.googlesource.gerrit.plugins.its.jira.restapi.JiraRestApi.java
private HttpURLConnection prepHttpConnection(String spec, String method, boolean withPayload) throws IOException { JiraURL url = baseUrl.withSpec(spec); ProxySelector proxySelector = ProxySelector.getDefault(); HttpURLConnection conn = url.openConnection(proxySelector); conn.setRequestProperty("Authorization", "Basic " + auth); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestMethod(method.toUpperCase()); if (withPayload) { conn.setDoOutput(true);/*from w ww . ja v a 2 s .c o m*/ } return conn; }
From source file:com.gallery.GalleryRemote.GalleryComm.java
protected GalleryComm(Gallery g, StatusUpdate su) { if (g == null) { throw new IllegalArgumentException("Must supply a non-null gallery."); }//from w w w . j a va 2s . com this.g = g; this.su = su; SingleClientConnManager cm = null; // Set all-trusting SSL manager, if necessary if (g.getUrl().getProtocol().equals("https")) { try { SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", sf, 443)); cm = new SingleClientConnManager(schemeRegistry); } catch (NoSuchAlgorithmException e) { Log.logException(Log.LEVEL_CRITICAL, MODULE, e); } } httpclient = new DefaultHttpClient(cm); // Use default proxy (as defined by the JVM) ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpclient.setRoutePlanner(routePlanner); // use GR User-Agent httpclient.removeRequestInterceptorByClass(RequestUserAgent.class); final String ua = g.getUserAgent(); httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { request.setHeader(HTTP.USER_AGENT, ua); } }); }
From source file:com.android.sdklib.internal.repository.UrlOpener.java
private static InputStream openWithHttpClient(String url, ITaskMonitor monitor) throws IOException, ClientProtocolException, CanceledByUserException { UserCredentials result = null;//w w w . j a v a 2s . c om String realm = null; // use the simple one final DefaultHttpClient httpClient = new DefaultHttpClient(); // create local execution context HttpContext localContext = new BasicHttpContext(); HttpGet httpget = new HttpGet(url); // retrieve local java configured network in case there is the need to // authenticate a proxy ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Set preference order for authentication options. // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in // servers that support both, as it is more secure. However, we don't seem to handle it // very well, so we leave it off the list. // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for // more info. List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); authpref.add(AuthPolicy.NTLM); httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); boolean trying = true; // loop while the response is being fetched while (trying) { // connect and get status code HttpResponse response = httpClient.execute(httpget, localContext); int statusCode = response.getStatusLine().getStatusCode(); // check whether any authentication is required AuthState authenticationState = null; if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // Target host authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); } if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // Proxy authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); } if (statusCode == HttpStatus.SC_OK) { // in case the status is OK and there is a realm and result, // cache it if (realm != null && result != null) { sRealmCache.put(realm, result); } } // there is the need for authentication if (authenticationState != null) { // get scope and realm AuthScope authScope = authenticationState.getAuthScope(); // If the current realm is different from the last one it means // a pass was performed successfully to the last URL, therefore // cache the last realm if (realm != null && !realm.equals(authScope.getRealm())) { sRealmCache.put(realm, result); } realm = authScope.getRealm(); // in case there is cache for this Realm, use it to authenticate if (sRealmCache.containsKey(realm)) { result = sRealmCache.get(realm); } else { // since there is no cache, request for login and password result = monitor.displayLoginCredentialsPrompt("Site Authentication", "Please login to the following domain: " + realm + "\n\nServer requiring authentication:\n" + authScope.getHost()); if (result == null) { throw new CanceledByUserException("User canceled login dialog."); } } // retrieve authentication data String user = result.getUserName(); String password = result.getPassword(); String workstation = result.getWorkstation(); String domain = result.getDomain(); // proceed in case there is indeed a user if (user != null && user.length() > 0) { Credentials credentials = new NTCredentials(user, password, workstation, domain); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); trying = true; } else { trying = false; } } else { trying = false; } HttpEntity entity = response.getEntity(); if (entity != null) { if (trying) { // in case another pass to the Http Client will be performed, close the entity. entity.getContent().close(); } else { // since no pass to the Http Client is needed, retrieve the // entity's content. // Note: don't use something like a BufferedHttpEntity since it would consume // all content and store it in memory, resulting in an OutOfMemory exception // on a large download. return new FilterInputStream(entity.getContent()) { @Override public void close() throws IOException { super.close(); // since Http Client is no longer needed, close it httpClient.getConnectionManager().shutdown(); } }; } } } // We get here if we did not succeed. Callers do not expect a null result. httpClient.getConnectionManager().shutdown(); throw new FileNotFoundException(url); }
From source file:net.sf.keystore_explorer.utilities.net.PacProxySelector.java
private String loadPacScript(String pacUrl) throws PacProxyException { URLConnection connection = null; // Save existing default proxy selector... ProxySelector defaultProxySelector = ProxySelector.getDefault(); try {/*ww w . j a va 2 s . c o m*/ // ...and set use of no proxy selector. We don't want to try and use any proxy to get the the pac script ProxySelector.setDefault(new NoProxySelector()); URL latestVersionUrl = new URL(pacUrl); connection = latestVersionUrl.openConnection(); InputStreamReader isr = null; StringWriter sw = null; try { isr = new InputStreamReader(connection.getInputStream()); sw = new StringWriter(); CopyUtil.copy(isr, sw); return sw.toString(); } finally { IOUtils.closeQuietly(isr); IOUtils.closeQuietly(sw); } } catch (IOException ex) { throw new PacProxyException( MessageFormat.format(res.getString("NoLoadPacScript.exception.message"), pacUrl), ex); } finally { // Restore saved default proxy selector ProxySelector.setDefault(defaultProxySelector); if ((connection != null) && (connection instanceof HttpURLConnection)) { ((HttpURLConnection) connection).disconnect(); } } }