类java.net.Proxy源码实例Demo

下面列出了怎么用java.net.Proxy的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: xxl-crawler   文件: RoundProxyMaker.java
@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());
}
 
源代码2 项目: jdk8u_jdk   文件: SocksConnectTimeout.java
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);
    }
}
 
源代码3 项目: http-builder-ng   文件: ApacheHttpBuilder.java
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();
    }
}
 
源代码4 项目: OpenAs2App   文件: HTTPUtil.java
/**
 * @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));

}
 
源代码5 项目: TorrentEngine   文件: ProxyLoginHandler.java
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 );
 }
 
源代码6 项目: openjdk-jdk8u   文件: HttpURLConnection.java
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>() {
 
源代码7 项目: lizzie   文件: AjaxHttpRequest.java
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);
}
 
源代码8 项目: letv   文件: p.java
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;
    }
}
 
源代码9 项目: netbeans   文件: ProxySelectorTest.java
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));
}
 
源代码10 项目: netbeans   文件: ProxyAutoConfigTest.java
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());
    }
}
 
源代码11 项目: nifi   文件: RestLookupService.java
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();
            });
        }
    }
}
 
源代码12 项目: CordovaYoutubeVideoPlayer   文件: RouteSelector.java
/** 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;
}
 
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;
}
 
源代码14 项目: IoTgo_Android_App   文件: Address.java
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);
}
 
protected HttpClient getNewHttpClient(URL url, Proxy p, int connectTimeout,
                                      boolean useCache)
    throws IOException {
    return HttpsClient.New(getSSLSocketFactory(), url,
                           getHostnameVerifier(), p,
                           useCache, connectTimeout, this);
}
 
源代码16 项目: embedded-cassandra   文件: RemoteArtifact.java
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;
}
 
源代码17 项目: cerberus-source   文件: FtpService.java
@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);
}
 
源代码18 项目: TencentKona-8   文件: HttpProxy.java
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);
        }
    }
}
 
源代码19 项目: wildfly-samples   文件: RouteSelector.java
/** 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();
    }
  }
}
 
源代码20 项目: Kalle   文件: OkHttpConnectFactory.java
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);
}
 
源代码21 项目: openjdk-jdk8u   文件: SocksIPv6Test.java
@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);
}
 
源代码22 项目: CordovaYoutubeVideoPlayer   文件: RouteSelector.java
/** 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();
    }
  }
}
 
源代码23 项目: nifi   文件: StandardProxyConfigurationService.java
@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());
}
 
源代码24 项目: openjdk-jdk8u-backup   文件: B8035158.java
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);
}
 
源代码25 项目: SmartIM   文件: SmartQQApi.java
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();
}
 
源代码26 项目: java-technology-stack   文件: ProxyFactoryBean.java
@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);
}
 
源代码27 项目: cordova-android-chromeview   文件: Route.java
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;
}
 
源代码28 项目: jdk8u60   文件: DelegateHttpsURLConnection.java
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;
}
 
源代码29 项目: openjdk-jdk8u   文件: DelegateHttpsURLConnection.java
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;
}
 
源代码30 项目: AndroidProjects   文件: Route.java
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;
}
 
 类所在包
 同包方法