java.net.Proxy Java Examples

The following examples show how to use java.net.Proxy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SocksConnectTimeout.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    try {
        serverSocket = new ServerSocket(0);

        (new Thread() {
            @Override
            public void run() { serve(); }
        }).start();

        Proxy socksProxy = new Proxy(Proxy.Type.SOCKS,
            new InetSocketAddress(InetAddress.getLocalHost(), serverSocket.getLocalPort()));

        test(socksProxy);
    } catch (IOException e) {
        unexpected(e);
    } finally {
        close(serverSocket);

        if (failed > 0)
            throw new RuntimeException("Test Failed: passed:" + passed + ", failed:" + failed);
    }
}
 
Example #2
Source File: ProxyAutoConfigTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void XXXtestGetProxyAutoConfigWithLocalInvalidPAC() throws URISyntaxException {
    List<String> pacFileLocations = new LinkedList<String>();
    for (File pacFile : new File[] {
        new File(getDataDir(), "pacFiles"),
        //new File(getDataDir(), "doesNotExist")
    }) {
        pacFileLocations.add(pacFile.getAbsolutePath());
        pacFileLocations.add("file://" + pacFile.getAbsolutePath());
        pacFileLocations.add(pacFile.toURI().toString());
    }
    for (String pacFileLoc : pacFileLocations) {
        ProxyAutoConfig pac = ProxyAutoConfig.get(pacFileLoc);
        assertNotNull(pac);
        URI uri = pac.getPacURI();
        assertNotNull(uri);
        List<Proxy> proxies = pac.findProxyForURL(new URI("http://netbeans.org"));
        assertEquals(1, proxies.size());
        assertEquals("DIRECT", proxies.get(0).toString());
    }
}
 
Example #3
Source File: HTTPUtil.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * @param protocol
 * @return
 * @throws OpenAS2Exception
 * @deprecated - use post method to send messages
 */
private static Proxy getProxy(String protocol) throws OpenAS2Exception {
    String proxyHost = Properties.getProperty(protocol + ".proxyHost", null);
    if (proxyHost == null) {
        proxyHost = System.getProperty(protocol + ".proxyHost");
    }
    if (proxyHost == null) {
        return Proxy.NO_PROXY;
    }
    String proxyPort = Properties.getProperty(protocol + ".proxyPort", null);
    if (proxyPort == null) {
        proxyPort = System.getProperty(protocol + ".proxyPort");
    }
    if (proxyPort == null) {
        throw new OpenAS2Exception("Missing PROXY port since Proxy host is set");
    }
    int port = Integer.parseInt(proxyPort);
    return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, port));

}
 
Example #4
Source File: ApacheHttpBuilder.java    From http-builder-ng with Apache License 2.0 6 votes vote down vote up
private Registry<ConnectionSocketFactory> registry(final HttpObjectConfig config) {
    final ProxyInfo proxyInfo = config.getExecution().getProxyInfo();

    final boolean isSocksProxied = (proxyInfo != null && proxyInfo.getProxy().type() == Proxy.Type.SOCKS);

    if (isSocksProxied) {
        return RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new SocksHttp(proxyInfo.getProxy()))
            .register("https", new SocksHttps(proxyInfo.getProxy(), sslContext(config),
                config.getExecution().getHostnameVerifier()))
            .build();
    } else {
        return RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslContext(config), config.getExecution().getHostnameVerifier()))
            .build();
    }
}
 
Example #5
Source File: RestLookupService.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void setProxy(OkHttpClient.Builder builder) {
    ProxyConfiguration config = proxyConfigurationService.getConfiguration();
    if (!config.getProxyType().equals(Proxy.Type.DIRECT)) {
        final Proxy proxy = config.createProxy();
        builder.proxy(proxy);

        if (config.hasCredential()){
            builder.proxyAuthenticator((route, response) -> {
                final String credential= Credentials.basic(config.getProxyUserName(), config.getProxyUserPassword());
                return response.request().newBuilder()
                        .header("Proxy-Authorization", credential)
                        .build();
            });
        }
    }
}
 
Example #6
Source File: ProxySelectorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAddAndSelect() {
  MyProxySelector selector = new MyProxySelector();
  assertNull(selector.getForType(MyProxyType.HTTP));
  assertNull(selector.getForType(MyProxyType.SOCKS));
  assertNull(selector.getForType(MyProxyType.FTP));
  assertEquals(Proxy.NO_PROXY, selector.select(httpURI).get(0));
  assertEquals(Proxy.NO_PROXY, selector.select(ftpURI).get(0));
  assertEquals(Proxy.NO_PROXY, selector.select(svnURI).get(0));
  final MyProxy http = new MyProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 8080)), MyProxyType.HTTP);
  final MyProxy ftp = new MyProxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("hehe.kill.yourself", 8080)), MyProxyType.FTP);
  final MyProxy socks = new MyProxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("localhost", 8080)), MyProxyType.SOCKS);
  selector.add(http);
  selector.add(ftp);
  selector.add(socks);
  assertNotNull(selector.getForType(MyProxyType.HTTP));
  assertNotNull(selector.getForType(MyProxyType.SOCKS));
  assertNotNull(selector.getForType(MyProxyType.FTP));
  assertEquals(http.getProxy(), selector.select(httpURI).get(0));
  assertEquals(ftp.getProxy(), selector.select(ftpURI).get(0));
  assertEquals(socks.getProxy(), selector.select(svnURI).get(0));
}
 
Example #7
Source File: p.java    From letv with Apache License 2.0 6 votes vote down vote up
private static HttpURLConnection a(Context context, String str) {
    try {
        URL url = new URL(str);
        if (context.getPackageManager().checkPermission(z[43], context.getPackageName()) == 0) {
            NetworkInfo activeNetworkInfo = ((ConnectivityManager) context.getSystemService(z[44])).getActiveNetworkInfo();
            if (!(activeNetworkInfo == null || activeNetworkInfo.getType() == 1)) {
                String extraInfo = activeNetworkInfo.getExtraInfo();
                if (extraInfo != null && (extraInfo.equals(z[40]) || extraInfo.equals(z[41]) || extraInfo.equals(z[42]))) {
                    return (HttpURLConnection) url.openConnection(new Proxy(Type.HTTP, new InetSocketAddress(z[45], 80)));
                }
            }
        }
        return (HttpURLConnection) url.openConnection();
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e2) {
        e2.printStackTrace();
        return null;
    }
}
 
Example #8
Source File: AjaxHttpRequest.java    From lizzie with GNU General Public License v3.0 6 votes vote down vote up
public void open(
    final String method,
    final URL url,
    boolean async,
    final String userName,
    final String password)
    throws IOException {
  this.abort();
  Proxy proxy = this.proxy;
  URLConnection c =
      proxy == null || proxy == Proxy.NO_PROXY ? url.openConnection() : url.openConnection(proxy);
  synchronized (this) {
    this.connection = c;
    this.async = async;
    this.requestMethod = method;
    this.requestURL = url;
    this.requestUserName = userName;
    this.requestPassword = password;
  }
  this.changeState(AjaxHttpRequest.STATE_LOADING, 0, null, null);
}
 
Example #9
Source File: RouteSelector.java    From CordovaYoutubeVideoPlayer with MIT License 6 votes vote down vote up
/** Returns the next proxy to try. May be PROXY.NO_PROXY but never null. */
private Proxy nextProxy() {
  // If the user specifies a proxy, try that and only that.
  if (userSpecifiedProxy != null) {
    hasNextProxy = false;
    return userSpecifiedProxy;
  }

  // Try each of the ProxySelector choices until one connection succeeds. If none succeed
  // then we'll try a direct connection below.
  if (proxySelectorProxies != null) {
    while (proxySelectorProxies.hasNext()) {
      Proxy candidate = proxySelectorProxies.next();
      if (candidate.type() != Proxy.Type.DIRECT) {
        return candidate;
      }
    }
  }

  // Finally try a direct connection.
  hasNextProxy = false;
  return Proxy.NO_PROXY;
}
 
Example #10
Source File: HttpURLConnection.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
protected HttpURLConnection(URL u, Proxy p, Handler handler)
    throws IOException {
super(checkURL(u));
requests = new MessageHeader();
responses = new MessageHeader();
userHeaders = new MessageHeader();
this.handler = handler;
instProxy = p;
if (instProxy instanceof sun.net.ApplicationProxy) {
    /* Application set Proxies should not have access to cookies
     * in a secure environment unless explicitly allowed. */
    try {
        cookieHandler = CookieHandler.getDefault();
    } catch (SecurityException se) { /* swallow exception */ }
} else {
    cookieHandler = java.security.AccessController.doPrivileged(
        new java.security.PrivilegedAction<CookieHandler>() {
        public CookieHandler run() {
            return CookieHandler.getDefault();
        }
    });
}
cacheHandler = java.security.AccessController.doPrivileged(
    new java.security.PrivilegedAction<ResponseCache>() {
 
Example #11
Source File: RoundProxyMaker.java    From xxl-crawler with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Proxy make() {
    if (super.proxyList==null || super.proxyList.size()==0) {
        return null;
    }

    if (super.proxyList.size() == 1) {
        super.proxyList.get(0);
    }

    int countVal = count.incrementAndGet();
    if (countVal > 100000) {
        countVal = 0;
        count.set(countVal);
    }

    return super.proxyList.get(countVal%super.proxyList.size());
}
 
Example #12
Source File: ProxyLoginHandler.java    From TorrentEngine with GNU General Public License v3.0 6 votes vote down vote up
public static InetSocketAddress
 getProxyAddress(
InetSocketAddress	target )
 {
  Proxy p = proxy_selector.getSOCKSProxy( DEFAULT_SOCKS_SERVER_ADDRESS, target  );
  
  	// always use a proxy here as the calling code should know what it is doing...
  
  if ( p.type() == Proxy.Type.SOCKS ){
	  
	  SocketAddress sa = p.address();
	  
	  if ( sa instanceof InetSocketAddress ){
		  
		  return((InetSocketAddress)sa);
	  }
  }
  
  return( DEFAULT_SOCKS_SERVER_ADDRESS );
 }
 
Example #13
Source File: BadProxySelector.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public List<Proxy> select(URI uri) {
    List<Proxy> proxies = new ArrayList<>();
    proxies.add(null);
    proxies.add(new Proxy(Proxy.Type.HTTP,
                          new InetSocketAddress("localhost", 0)));
    return proxies;
}
 
Example #14
Source File: DelegateHttpsURLConnection.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
DelegateHttpsURLConnection(URL url, Proxy p,
        sun.net.www.protocol.http.Handler handler,
        com.sun.net.ssl.HttpsURLConnection httpsURLConnection)
        throws IOException {
    super(url, p, handler);
    this.httpsURLConnection = httpsURLConnection;
}
 
Example #15
Source File: Address.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
public Address(String uriHost, int uriPort, SSLSocketFactory sslSocketFactory,
    HostnameVerifier hostnameVerifier, OkAuthenticator authenticator, Proxy proxy,
    List<String> transports) throws UnknownHostException {
  if (uriHost == null) throw new NullPointerException("uriHost == null");
  if (uriPort <= 0) throw new IllegalArgumentException("uriPort <= 0: " + uriPort);
  if (authenticator == null) throw new IllegalArgumentException("authenticator == null");
  if (transports == null) throw new IllegalArgumentException("transports == null");
  this.proxy = proxy;
  this.uriHost = uriHost;
  this.uriPort = uriPort;
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
  this.authenticator = authenticator;
  this.transports = Util.immutableList(transports);
}
 
Example #16
Source File: RouteSelector.java    From bluemix-parking-meter with MIT License 5 votes vote down vote up
/**
 * Clients should invoke this method when they encounter a connectivity
 * failure on a connection returned by this route selector.
 */
public void connectFailed(Connection connection, IOException failure) {
  Route failedRoute = connection.getRoute();
  if (failedRoute.getProxy().type() != Proxy.Type.DIRECT && proxySelector != null) {
    // Tell the proxy selector when we fail to connect on a fresh connection.
    proxySelector.connectFailed(uri, failedRoute.getProxy().address(), failure);
  }

  routeDatabase.failed(failedRoute, failure);
}
 
Example #17
Source File: OkHttpConnectFactory.java    From Kalle with Apache License 2.0 5 votes vote down vote up
private HttpURLConnection open(URL url, Proxy proxy) {
    OkHttpClient newClient = mClient.newBuilder().proxy(proxy).build();
    String protocol = url.getProtocol();
    if (protocol.equalsIgnoreCase("http")) return new OkHttpURLConnection(url, newClient);
    if (protocol.equalsIgnoreCase("https")) return new OkHttpsURLConnection(url, newClient);
    throw new IllegalArgumentException("Unexpected protocol: " + protocol);
}
 
Example #18
Source File: FtpService.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setProxy(FTPClient client, String system, AppService myResponse) {
    String proxyHost = parameterService.getParameterStringByKey("cerberus_proxy_host", "",
            DEFAULT_PROXY_HOST);
    int proxyPort = parameterService.getParameterIntegerByKey("cerberus_proxy_port", "",
            DEFAULT_PROXY_PORT);

    myResponse.setProxy(true);
    myResponse.setProxyHost(proxyHost);
    myResponse.setProxyPort(proxyPort);

    SocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
    Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
    if (parameterService.getParameterBooleanByKey("cerberus_proxyauthentification_active", system,
            DEFAULT_PROXYAUTHENT_ACTIVATE)) {
        Authenticator.setDefault(
                new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                String proxyUser = parameterService.getParameterStringByKey("cerberus_proxyauthentification_user", "", DEFAULT_PROXYAUTHENT_USER);
                String proxyPassword = parameterService.getParameterStringByKey("cerberus_proxyauthentification_password", "", DEFAULT_PROXYAUTHENT_PASSWORD);
                myResponse.setProxyWithCredential(true);
                myResponse.setProxyUser(proxyUser);
                return new PasswordAuthentication(
                        proxyUser, proxyPassword.toCharArray()
                );
            }
        }
        );
    }
    client.setProxy(proxy);
}
 
Example #19
Source File: SocksIPv6Test.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test(groups = "unit")
public void testSocksOverIPv6() throws Exception {
    if (!shouldRun) return;

    Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("::1",
            socks.getPort()));
    URL url = new URL("http://[::1]:" + server.getAddress().getPort());
    java.net.URLConnection conn = url.openConnection(proxy);
    String actual = "";
    try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(conn.getInputStream()))) {
        actual = reader.readLine();
    }
    assertEquals(actual, response);
}
 
Example #20
Source File: RouteSelector.java    From CordovaYoutubeVideoPlayer with MIT License 5 votes vote down vote up
/** Resets {@link #nextProxy} to the first option. */
private void resetNextProxy(URI uri, Proxy proxy) {
  this.hasNextProxy = true; // This includes NO_PROXY!
  if (proxy != null) {
    this.userSpecifiedProxy = proxy;
  } else {
    List<Proxy> proxyList = proxySelector.select(uri);
    if (proxyList != null) {
      this.proxySelectorProxies = proxyList.iterator();
    }
  }
}
 
Example #21
Source File: DownloadOkHttp3ConnectionTest.java    From okdownload with Apache License 2.0 5 votes vote down vote up
@Test
public void createCreator_withBuilder_Assigned() throws IOException {
    final OkHttpClient.Builder builder = new OkHttpClient.Builder();
    final Proxy proxy = mock(Proxy.class);
    builder.proxy(proxy);
    DownloadOkHttp3Connection.Factory factory = new DownloadOkHttp3Connection.Factory()
            .setBuilder(builder);

    assertThat(factory.builder()).isEqualTo(builder);

    DownloadOkHttp3Connection connection = (DownloadOkHttp3Connection) factory.create(URL);

    assertThat(connection.client.proxy()).isEqualTo(proxy);
}
 
Example #22
Source File: Route.java    From AndroidProjects with MIT License 5 votes vote down vote up
public Route(Address address, Proxy proxy, InetSocketAddress inetSocketAddress) {
  if (address == null) {
    throw new NullPointerException("address == null");
  }
  if (proxy == null) {
    throw new NullPointerException("proxy == null");
  }
  if (inetSocketAddress == null) {
    throw new NullPointerException("inetSocketAddress == null");
  }
  this.address = address;
  this.proxy = proxy;
  this.inetSocketAddress = inetSocketAddress;
}
 
Example #23
Source File: StandardProxyConfigurationService.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnEnabled
public void setConfiguredValues(final ConfigurationContext context) {
    configuration = new ProxyConfiguration();
    configuration.setProxyType(Proxy.Type.valueOf(context.getProperty(PROXY_TYPE).getValue()));
    configuration.setProxyServerHost(context.getProperty(PROXY_SERVER_HOST).evaluateAttributeExpressions().getValue());
    configuration.setProxyServerPort(context.getProperty(PROXY_SERVER_PORT).evaluateAttributeExpressions().asInteger());
    configuration.setProxyUserName(context.getProperty(PROXY_USER_NAME).evaluateAttributeExpressions().getValue());
    configuration.setProxyUserPassword(context.getProperty(PROXY_USER_PASSWORD).evaluateAttributeExpressions().getValue());
}
 
Example #24
Source File: DelegateHttpsURLConnection.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
DelegateHttpsURLConnection(URL url, Proxy p,
        sun.net.www.protocol.http.Handler handler,
        javax.net.ssl.HttpsURLConnection httpsURLConnection)
        throws IOException {
    super(url, p, handler);
    this.httpsURLConnection = httpsURLConnection;
}
 
Example #25
Source File: DelegateHttpsURLConnection.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
DelegateHttpsURLConnection(URL url, Proxy p,
        sun.net.www.protocol.http.Handler handler,
        javax.net.ssl.HttpsURLConnection httpsURLConnection)
        throws IOException {
    super(url, p, handler);
    this.httpsURLConnection = httpsURLConnection;
}
 
Example #26
Source File: WebUtils.java    From alipay-sdk with Apache License 2.0 5 votes vote down vote up
private static HttpURLConnection getConnection(URL url, String method, String ctype,
                                               String proxyHost, int proxyPort) throws IOException {
    Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
    return getConnection(url, method, ctype, proxy);
}
 
Example #27
Source File: B8035158.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
void run() {
    System.out.printf("urlhost=%s properties=%s: proxied? %s%n",
            urlhost, localProperties, expectedProxying);

    List<Proxy> proxies = withSystemPropertiesSet(localProperties,
            () -> ProxySelector.getDefault().select(
                    URI.create(urlhost))
    );

    verify(proxies);
}
 
Example #28
Source File: SmartQQApi.java    From SmartIM with Apache License 2.0 5 votes vote down vote up
public SmartQQApi(Proxy proxy) {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.cookieJar(cookieJar);
    builder.hostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    });
    if (proxy != null) {
        builder.proxy(proxy);
    }
    this.client = builder.build();
}
 
Example #29
Source File: Route.java    From cordova-android-chromeview with Apache License 2.0 5 votes vote down vote up
public Route(Address address, Proxy proxy, InetSocketAddress inetSocketAddress,
    boolean modernTls) {
  if (address == null) throw new NullPointerException("address == null");
  if (proxy == null) throw new NullPointerException("proxy == null");
  if (inetSocketAddress == null) throw new NullPointerException("inetSocketAddress == null");
  this.address = address;
  this.proxy = proxy;
  this.inetSocketAddress = inetSocketAddress;
  this.modernTls = modernTls;
}
 
Example #30
Source File: ProxyFactoryBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws IllegalArgumentException {
	Assert.notNull(this.type, "Property 'type' is required");
	Assert.notNull(this.hostname, "Property 'hostname' is required");
	if (this.port < 0 || this.port > 65535) {
		throw new IllegalArgumentException("Property 'port' value out of range: " + this.port);
	}

	SocketAddress socketAddress = new InetSocketAddress(this.hostname, this.port);
	this.proxy = new Proxy(this.type, socketAddress);
}