Java Code Examples for java.net.Proxy

The following examples show how to use java.net.Proxy. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: xxl-crawler   Source File: RoundProxyMaker.java    License: 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 2
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 3
Source Project: http-builder-ng   Source File: ApacheHttpBuilder.java    License: 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 4
Source Project: OpenAs2App   Source File: HTTPUtil.java    License: 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 5
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 6
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 7
Source Project: lizzie   Source File: AjaxHttpRequest.java    License: 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 8
Source Project: letv   Source File: p.java    License: 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 9
Source Project: netbeans   Source File: ProxySelectorTest.java    License: 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 10
Source Project: netbeans   Source File: ProxyAutoConfigTest.java    License: 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 11
Source Project: nifi   Source File: RestLookupService.java    License: 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 12
Source Project: CordovaYoutubeVideoPlayer   Source File: RouteSelector.java    License: 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 13
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 14
Source Project: IoTgo_Android_App   Source File: Address.java    License: 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 15
protected HttpClient getNewHttpClient(URL url, Proxy p, int connectTimeout,
                                      boolean useCache)
    throws IOException {
    return HttpsClient.New(getSSLSocketFactory(), url,
                           getHostnameVerifier(), p,
                           useCache, connectTimeout, this);
}
 
Example 16
Source Project: embedded-cassandra   Source File: RemoteArtifact.java    License: Apache License 2.0 5 votes vote down vote up
private static URLConnection connect(URL url, Duration readTimeout, Duration connectTimeout,
		@Nullable Proxy proxy) throws IOException {
	URLConnection connection = (proxy != null) ? url.openConnection(proxy) : url.openConnection();
	connection.setConnectTimeout(Math.toIntExact(connectTimeout.toMillis()));
	connection.setReadTimeout(Math.toIntExact(readTimeout.toMillis()));
	return connection;
}
 
Example 17
Source Project: cerberus-source   Source File: FtpService.java    License: 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 18
Source Project: TencentKona-8   Source File: HttpProxy.java    License: GNU General Public License v2.0 5 votes vote down vote up
void test() throws Exception {
    InetSocketAddress proxyAddress = new InetSocketAddress(proxyHost, proxyPort);
    Proxy httpProxy = new Proxy(Proxy.Type.HTTP, proxyAddress);

    try (ServerSocket ss = new ServerSocket(0);
         Socket sock = new Socket(httpProxy)) {
        sock.setSoTimeout(SO_TIMEOUT);
        sock.setTcpNoDelay(false);

        InetSocketAddress externalAddress =
            new InetSocketAddress(InetAddress.getLocalHost(), ss.getLocalPort());

        out.println("Trying to connect to server socket on " + externalAddress);
        sock.connect(externalAddress);
        try (Socket externalSock = ss.accept()) {
            // perform some simple checks
            check(sock.isBound(), "Socket is not bound");
            check(sock.isConnected(), "Socket is not connected");
            check(!sock.isClosed(), "Socket should not be closed");
            check(sock.getSoTimeout() == SO_TIMEOUT,
                    "Socket should have a previously set timeout");
            check(sock.getTcpNoDelay() ==  false, "NODELAY should be false");

            simpleDataExchange(sock, externalSock);
        }
    }
}
 
Example 19
Source Project: wildfly-samples   Source File: RouteSelector.java    License: 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 20
Source Project: Kalle   Source File: OkHttpConnectFactory.java    License: 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 21
Source Project: openjdk-jdk8u   Source File: SocksIPv6Test.java    License: 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 22
Source Project: CordovaYoutubeVideoPlayer   Source File: RouteSelector.java    License: 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 23
Source Project: nifi   Source File: StandardProxyConfigurationService.java    License: 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
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 25
Source Project: SmartIM   Source File: SmartQQApi.java    License: 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 26
Source Project: java-technology-stack   Source File: ProxyFactoryBean.java    License: 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);
}
 
Example 27
Source Project: cordova-android-chromeview   Source File: Route.java    License: 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 28
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 29
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 30
Source Project: AndroidProjects   Source File: Route.java    License: 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;
}